一個線程可以在其它線程之上調用join()方法,其效果是等待一段時間直到第二個線程結束才繼續執行。如果某個線程在另一個線程t上調用t.join(),此線程將被掛起,直到目標線程t結束才恢復(即t.isAlive()返回假)。
也可以在調用join()方法時帶上一個超時參數(單位可以試毫秒,或者毫秒和納秒),這樣如果目標線程在這段時間到期時還沒有結束的話,join()方法總能返回。
對join()方法的調用可以被中斷,做法是在調用線程上調用interrupted()方法,這時需要用到try-catch子句。
class Sleeper extends Thread{
private 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. "+" is interrupted: "+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();
}
public void run() {
try {
sleeper.join();
}catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println(getName()+" join completed");
}
}
public class Joining {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sleeper sleepy=new Sleeper("Sleepy",1500),
grumpy=new Sleeper("grumpy",1500);
Joiner dopey=new Joiner("Dopey",sleepy),
doc=new Joiner("Doc",grumpy);
grumpy.interrupt();
}
}
/*
grumpy was interrupted. is interrupted: false
Doc join completed
Sleepy has awakened
Dopey join completed
*/