虽然在网上遇到一些问题,但我发现了这一点。不知道如何解决这个问题。如何让两个线程彼此等待执行任务?
我想线程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();
}
}
我不知道为什么,但字段名称前使用下划线让我想杀人的东西! – 2013-03-25 00:25:27