Deadlock

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

package Cocurrent;

public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        /**
         * 向friend鞠躬
         * @param bower
         */
        public synchronized void bow(Friend friend) {
        	//用println并不能触发死锁的情况,因为第二个线程起来的时候,第一个已经执行完了。
//            System.out.println(this.getName() + " bowed to "+friend.getName());
            System.out.format("%s has bowed to %s!%n", 
                  this.name, friend.getName());
            friend.bowBack(this);
        }
        /**
         * 向friend回礼
         * @param bower
         */
        public synchronized void bowBack(Friend friend) {
//            System.out.println(this.getName() + " bowed back to "+friend.getName());
        	System.out.format("%s has bowed back to %s!%n", 
                    this.name, friend.getName());
        }
    }

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


分析和结果
第一个线程起来,获取A的锁,A向G鞠躬,等待G的锁,然后G执行回礼
第二个线程起来,获取G的锁,G向A鞠躬,等待A的锁,然后A执行回礼
但A和G的方法都无法退出,互相等待。
因此造成了死锁
执行结果:
Gaston has bowed to Alphonse!
Alphonse has bowed to Gaston!

程序曾用println代替,但是发现没有触发死锁的条件,必须A向G鞠躬的同时并且未从该方法中退出,G向A鞠躬,才触发。

你可能感兴趣的:(Lock)