0

インターネットでいくつかの問題を経験しているときに、私はこれを見つけました。これを解決する方法がわかりません。

最初にthread-1を実行してfooを計算して待機し、次にthread-2を実行してfooを計算し、最後にthread-1を続行してfooを出力して実行を完了させます。

過去1時間から考えていて解決できません。どんな助けでも大歓迎です。ありがとう。

public class ThreadTest {

    private static class Thread01 extends Thread {

        private Thread02 _thread02; 
        public int foo = 0;

        public void setThread02(Thread02 thread02) {
            _thread02 = thread02;
        }

        public void run() {

            try {
                for (int i = 0; i < 10; i++) foo += i;
                synchronized (this) { this.notify(); }
                synchronized (_thread02) { _thread02.wait(); }
                System.out.println("Foo: " + _thread02.foo);
            } catch (InterruptedException ie) { ie.printStackTrace(); }
        }
    }


private static class Thread02 extends Thread {

        private final Thread01 _thread01; public int foo = 0;

        public Thread02(Thread01 thread01) {
            _thread01 = thread01;
        }

        public void run() {

            try {
                synchronized (_thread01) { _thread01.wait(); }
                foo = _thread01.foo;
                for (int i = 0; i < 10; i++) foo += i;
                synchronized (this) { this.notify(); }
            } catch (InterruptedException ie) { ie.printStackTrace(); }
        }
    }

    public static void main(String[] args) throws Exception {

        Thread01 thread01 = new Thread01();
        Thread02 thread02 = new Thread02(thread01);
        thread01.setThread02(thread02);

        thread01.start(); 
        thread02.start();
        thread01.join();
        thread02.join();
    }
}
4

2 に答える 2

3

あなたのコードをあまり見ていなくても、私はそれがこのように機能すると思います:

スレッド1はfooを計算し、スレッド2を作成して開始します。スレッド1はを呼び出しますthread2.join()。これにより、スレッド2が終了するまでスレッド1が中断されます。次に、スレッド1の最終コードを続行します。

通知は必要ありません。1つだけ簡単join()です。

于 2013-03-25T00:22:13.207 に答える
2

このような通知/待機コードの代替手段の1つは、BlockingQueueのように使用することですLinkedBlockingQueue。2BlockingQueue秒の場合、2つのスレッドは、複雑でバグが多い可能性のあるすべての待機コードと通知コードを記述しなくても、互いに待機してメッセージをやり取りできます。

于 2013-03-25T11:40:41.180 に答える