Thinking in java 第21章 并发 12.2.11 加入一个线程
程序员文章站
2022-05-07 08:45:33
...
一个线程可以在其他线程之上调用join()方法,其效果是等待一段时间直到第二个线程结束才继续执行。如果某个线程在另一个线程T上调用T.join(),此线程将被挂起,知道目标线程结束才恢复(t.isAlive() == false)
也可以在调用join()时带上一个超时参数(单位时间自己决定),如果目标线程在这个时间没有结束,join()也将返回。
对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法,这时需要用到try - catch
下面是一个demo:
class Sleeper extends Thread{
private final int duration;
public Sleeper(String name,int sleepTime){
super(name);
duration = sleepTime;
start();
}
public void run(){
try {
sleep(duration);
} catch (InterruptedException e) {
System.out.println(getName() + "was interrupted. " + "isInterrupted(): " + isInterrupted());
return;
}
System.out.println(getName() + " has awakened");
}
}
class Joiner extends Thread {
private Sleeper sleeper;
public Joiner(String name,Sleeper sleeper){
super(name);
this.sleeper = sleeper;
start();
}
@Override
public void run(){
try {
sleeper.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " join completed");
}
}
public class Joining {
public static void main(String[] args) {
Sleeper sleeper = new Sleeper("Sleepy",1500);
Sleeper grumpy = new Sleeper("Grumpy",1500);
Joiner dopey = new Joiner("Dopey",sleeper);
Joiner doc = new Joiner("Doc",grumpy);
grumpy.interrupt();
}
}
sleeper是一个Thread ,他要休眠一段时间,在这期间,有可能是正常返回,也有可能调用了Interrupte方法而抛出异常,interrupte()方法给线程加上了一个状态,说明当前线程已经中断,isInterrupted()是返回这个状态值,并刷新这个状态,而异常捕获也会清理这个状态值,所以异常捕获种,isInterrupted()总是false.
下面是结果:
Grumpywas interrupted. isInterrupted(): false
Doc join completed
Sleepy has awakened
Dopey join completed