线程的唤醒interrupt
作者:binsleep、wait的进程都可以被interrupt打断,以此可以避免死等待
public class Part5 {
private final static String PREFIX = "MARK-";
public static void main(String[] args) throws Exception{
threadSleep();
}
/**
* 线程的interrupt
* @throws Exception
*/
private static void threadSleep() throws Exception{
Thread thread = new Thread(() -> {
try {
//推荐使用封装的TimeUnit方法
System.out.println("线程开始sleep 1分钟");
TimeUnit.MINUTES.sleep(1);
System.out.println("被打断的话,sleep后面的不会执行了");
}catch (Exception e) {
System.out.println("线程被打断sleep,继续执行");
}
});
//启动线程
thread.start();
//sleep 5 s
TimeUnit.SECONDS.sleep(5);
//打断线程
thread.interrupt();
}
}
interrupt不配被触发的情况,值得注意的是,如果非block情况,线程是不会被interrupt打断的。
Thread t1=new Thread(){
@Override
public void run(){
while(true){
System.out.println("未被中断");
}
}
};
t1.start();
TimeUnit.SECONDS.sleep(2);
t1.interrupt();
通过改写如下代码,自行判断是否被打断,
while(true && !this.isInterrupted()){
System.out.println("未被中断");
}