线程的休眠是可以由其它线程打断,Thread类中提供有中断执行的处理方法
判断线程是否被打断(返回true被中断,返回false没被中断)
public boolean isInterrupted()
中断线程执行
public void interrupt()
线程中断执行操作(所有正在执行的线程都可以被中断,但要进行异常处理)
public class TestThread {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(()-> {
System.out.println("休息10S");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("休息不足");
}
});
thread.start(); //开始休息
thread.sleep(1000);
if(!thread.isInterrupted()) {
System.out.println("打扰休息");
thread.interrupt(); //中断执行
}
}
}
结果如下