インターネットでいくつかの問題を経験しているときに、私はこれを見つけました。これを解決する方法がわかりません。
最初に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();
}
}