在互联网上遇到一些问题时,我发现了这个。不知道如何解决这个问题。
我希望线程 1 首先运行并计算 foo 并等待,然后希望线程 2 运行并计算 foo,最后希望线程 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();
}
}