练习书上的代码。作为笔记吧
package com;
class Sleeper extends Thread {
private int duration;
public Sleeper(String name, int sleepTime) {
super(name);
this.duration = sleepTime;
}
@Override
public void run() {
try {
System.out.println(getName() + "开始等待" + duration / 1000 + "秒");
sleep(duration);
} catch (InterruptedException e) {
// 如果线程中断异常被try catch ,那么线程的isInterrupted()将返回false
System.out.println(getName() + "线程是中断的吗" + isInterrupted());
}
System.out.println(getName() + "执行完成");
}
}
class Joiner extends Thread {
private Sleeper sleeper;
public Joiner(String name, Sleeper sleeper) {
super(name);
this.sleeper = sleeper;
}
@Override
public void run() {
try {
/*
* 叫join可能不太符合意思。个人感觉应该叫等待,当然不是object的wait方法的作用。 join调用后代表
* 当前线程(Joiner)将等待
* sleeper线程执行完毕,当前线程才会向下执行。也就是说,在sleeper线程执行完之前一直是阻塞的
*/
sleeper.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "执行完成");
}
}
public class Joining {
public static void main(String[] args) {
Sleeper sleeper = new Sleeper("睡眠的线程", 5000);
sleeper.start();
new Joiner("被在run中调用其他线程join方法的线程", sleeper).start();
sleeper.interrupt();
}
}
附上输出结果
----------------------------------------------------------
睡眠的线程开始等待5秒
睡眠的线程线程是中断的吗false
睡眠的线程执行完成
被在run中调用其他线程join方法的线程执行完成
----------------------------------------------------------
代码中有详细的注释,就不说明了。