[英]Make one thread wait for another to finish
我有两个线程类:一个打印从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();
}
}
您可以在线程启动之前在该线程上调用join
。 那行不通; 在这种情况下, join
将立即返回,而不必等到另一个线程启动和稍后停止。 您可以在API文档中看到以下内容:
Thread.join()
此实现使用的循环
this.wait
电话空调上this.isAlive
。
Thread.isAlive()
测试此线程是否仍然存在。 如果线程已经启动但尚未死亡, 则该线程是活动的。
在main
方法中对语句重新排序
t1.t.start();
t2.t.start();
t1.halt(t2.t); //wait for the 100-109 thread to finish
编辑以在评论中回答您的问题:
如果你想在线程AThread
等待的线程BThread
做的工作之前完成,那么你就需要调用join
在AThread.run
,并改变你的main
方法:
class AThread implements Runnable {
Thread t;
Thread threadToWaitFor;
AThread(Thread threadToWaitFor) {
t = new Thread(this);
this.threadToWaitFor = threadToWaitFor;
}
public void run() {
// First wait for the other thread to finish
threadToWaitFor.join();
// ...
}
// ...
}
public class WaitForThread {
public static void main(String[] args) {
BThread t2 = new BThread();
AThread t1 = new AThread(t2.t);
t2.t.start();
t1.t.start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.