加入一个线程
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." + "isInterrupted():" + isInterrupted());
}
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) {
Sleeper
sleepy = new Sleeper("Sleepy", 1500),
grumpy = new Sleeper("Grumpy",1500);
Joiner
dopey = new Joiner("Dopey", sleepy),
doc = new Joiner("Doc", grumpy);
grumpy.interrupt();
}
}
- 如果某个线程执行过程中,用
t.join()
调用另一个执行的线程t,那么此线程将被挂起,知道t结束才恢复 - 可以在调用
join()
时带上一个参数,如果目标线程在这段时间没有结束的话,join
方法总能返回 join()
方法也可以被中断,在被调用的线程上调用interrupt()
方法- 调用
Interrupt()
方法,给线程设置一个标记来表示已中断。但是在Interrupt
被捕获时,这个标记被清除,isInterrupt
总为false
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。