雖然在網上遇到一些問題,但我發現了這一點。不知道如何解決這個問題。如何讓兩個線程彼此等待執行任務?
我想線程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