Deadlock

2172 ワード

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はお返しを実行します
2番目のスレッドは起きて、Gのロックを取得して、GはAにお辞儀をして、Aのロックを待って、それからAはお返しを実行します
しかしAとGの方法はいずれも退出することができなくて、互いに待ちます.
デッドロックが発生しました
実行結果:
Gaston has bowed to Alphonse!
Alphonse has bowed to Gaston!
プログラムはprintlnで置き換えられたが,デッドロックをトリガーする条件がなく,AがGにお辞儀をすると同時にこの方法から退出せず,GがAにお辞儀をしなければトリガーされないことが分かった.