我有兩個線程類:一個打印數字從0到9,另一個從100到109.我想要的是讓第一個線程等待另一個完成。爲此,我使用了join()
方法,但它不起作用。請告訴我哪裏出錯:使一個線程等待另一個完成
//demonstrates the use of join() to wait for another thread to finish
class AThread implements Runnable {
Thread t;
AThread() {
t = new Thread(this);
}
public void run() {
try {
for (int i=0; i<10; i++) {
System.out.println(i);
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
public void halt(Thread th) {
try {
th.join();
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
}
//a different thread class (we distinguish threads by their output)
class BThread implements Runnable {
Thread t;
BThread() {
t = new Thread(this);
}
public void run() {
try {
for (int i=100; i<110; i++) {
System.out.println(i);
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
}
public class WaitForThread {
public static void main(String[] args) {
AThread t1 = new AThread();
BThread t2 = new BThread();
t1.t.start();
t1.halt(t2.t); //wait for the 100-109 thread to finish
t2.t.start();
}
}
爲什麼不使用wait()和notify方法實現它?它對於內部線程通信更有意義。 – BatScream 2014-11-23 07:27:05
@BatScream我只是在學習繩索,實際上。 :-) – dotslash 2014-11-23 07:34:15