我有两个线程类:一个打印数字从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