java多线程(Thread)之死锁(Deadlock)

概念:死锁是一种在多线程协作时永久堵塞的一种状态.(Deadlock describes a situation where two or more threads are blocked forever)。

场景举例一:A和B是好伙伴,他们见面是通常先向对方鞠躬,然后保持鞠躬的状态,等待对方回应自己的鞠躬。(通常情况下A先鞠躬,然后B鞠躬回应A,A起身)---->(而后后B鞠躬,A鞠躬回应B),见面礼仪结束。但当A和B同时鞠躬的时候就尴尬了。因为A和B都这时都在等待对方起来。

代码如下

public class Deadlock {
    static class Friend {
        private final String name;

        public Friend(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public synchronized void bow(Friend bower) {
            System.out.format("%s 向  %s 鞠躬, %s 等待%s回应他的鞠躬", this.name, bower.getName(), this.name, bower.getName());
            System.out.println();
            bower.bowBack(this);
        }

        public synchronized void bowBack(Friend bower) {
            System.out.format("%s 回应  %s 的鞠躬", this.name, bower.getName());
            System.out.println();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final Friend alphonse = new Friend("A");
        final Friend gaston = new Friend("B");
        new Thread(new Runnable() {
            public void run() {
                alphonse.bow(gaston);
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                gaston.bow(alphonse);
            }
        }).start();
    }
}

结果

原文地址:https://www.cnblogs.com/jinliang374003909/p/12911563.html