Javaのデッドロック二つのスレッドを使用してシーケンスを印刷しながら、

真のキラー:

私は2つのスレッドを使用して代わりに奇数と偶数を印刷しようとしました。しかし、プログラムはデッドロックに入りました。私はそれがデッドロックに入っている理由を理解することはできませんよ。デバッグモードでは、プログラムは動作が異なります。これは、1つの2デッドロックを出力します。この動作は予想外です。

予想される出力

1
2
3
4
odd thread ends here    
even thread ends here    
main thread ends here

電流出力

1
2
3
4
odd thread ends here
(Deadlock)

ここではJavaのコードがあります

public class PrintSequence {    
    public static void main(String[] args) {
        EvenOddPrinter printer = new EvenOddPrinter(false, 1, 4);
        Thread odd = new Thread(new Runnable() {    
            @Override
            public void run() {
                printer.printOdd();    
            }
        });
        Thread even = new Thread(new Runnable() {
            @Override
            public void run() {
                printer.printEven();
            }
        });
        odd.start();
        even.start();
        try {
            odd.join();
            System.out.println("odd thread ends here");
            even.join();
            System.out.println("even thread ends here");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main thread ends here");
    }

}

class EvenOddPrinter {

    private boolean isEven;
    private int index;
    private int maxNumber;

    public EvenOddPrinter(boolean isEven, int index, int maxNumber) {
        super();
        this.isEven = isEven;
        this.index = index;
        this.maxNumber = maxNumber;
    }

    public synchronized void printOdd () {
        while(index < maxNumber) {
            if(!isEven) {
                System.out.println(index);
                index++;
                isEven = true;
                notify();
            }
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }   
    public synchronized void printEven() {
        while(index <= maxNumber) {
            if(isEven) {
                System.out.println(index);
                index++;
                isEven = false;
                notify();
            }
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

これを固定で缶誰かの助けを私に?

WJS:

とき奇数仕上げ、それもスレッドに通知することはありません。だから、これを行います。

    public synchronized void printOdd () {
        while(index < maxNumber) {
            if(!isEven) {
                System.out.println(index);
                index++;
                isEven = true;
                notify();
            }
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        notify(); // add a notify here
    }   

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=361713&siteId=1