115-Thread中断Interrupt方法详细讲解
interrupt()
中断此线程
interrupted()
测试当前线程是否已被中断。
isInterrupted()
测试此线程是否已被中断。
interrupt()
仅仅是修改interrupt的状态。必须是wait()
、join()
、sleep()
的时候才会抛出异常中断线程。
Thread t1 = new Thread("t1") {
@Override
public void run() {
while (true) {
// todo...
}
}
};
t1.start();
// start之后处于runnable,并不一定马上就会running。所以设置短暂休眠等待t1启动
Thread.sleep(100);
System.out.println(t1.isInterrupted());// false
t1.interrupt();
System.out.println(t1.isInterrupted());// true
线程状态改变,不会捕获到打断信号
System.out.println(">>" + this.isInterrupted());
sleep()
。线程状态改变,且捕获到打断信号try { Thread.sleep(1_000); } catch (InterruptedException e) { System.out.println("收到打断信号。"); e.printStackTrace(); }
wait()
。线程状态改变,且捕获到打断信号使用
wait()
必须给一个monitor,monitor需使用synchronized包裹。private static final Object MONITOR = new Object();
synchronized (MONITOR) { try { MONITOR.wait(1_000); } catch (InterruptedException e) { e.printStackTrace(); } }
join()
。线程状态改变,且捕获到打断信号注意:
t3.join();
这里join的不是t3线程,而是main线程。所以需要对main线程进行interrupt()
Thread t3 = new Thread(() -> { while (true) {} }, "t3"); t3.start(); Thread main = Thread.currentThread(); Thread t31 = new Thread(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } main.interrupt(); }); t31.start(); try { // 这里join的不是t3线程,而是main线程 t3.join(); } catch (InterruptedException e) { e.printStackTrace(); }
非静态isInterrupted()
和静态interrupted()
区别:
在实现Runnable接口创建任务实例时,
isInterrupted()
将不能被获取Thread t2 = new Thread(() -> { while (true) { synchronized (MONITOR) { try { MONITOR.wait(1_000); } catch (InterruptedException e) { // 获取不到isInterrupted() // System.out.println("wait()->" + isInterrupted()); System.out.println("wait()->" + Thread.interrupted()); e.printStackTrace(); } } } }, "t2");
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 tuyrk@qq.com
文章标题:115-Thread中断Interrupt方法详细讲解
文章字数:397
本文作者:神秘的小岛岛
发布时间:2019-11-14, 09:12:31
最后更新:2019-12-25, 11:01:33
原始链接:https://www.tuyrk.cn/wang-thread/115-thread-interrupt/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。