Java如何实现线程中断?
通过调用Thread类的实例方法interrupt。如下:
Thread thread = new Thread(){ @Override public void run() { if(isInterrupted()){ System.out.println("interrupt"); } } }; thread.start(); thread.interrupt();
线程中断后线程会立即停止执行吗?
NO。 而如果线程未阻塞,或未关心中断状态,则线程会正常执行,不会被打断。
Thread.interrupt()的官方解释是这样的:
If this thread is blocked in an invocation of the
Object#wait() wait(), { Object#wait(long) wait(long)}, or { Object#wait(long, int) wait(long, int)} methods of the { Object} class, or of the { #join()}, { #join(long)}, { #join(long, int)}, { #sleep(long)}, or { #sleep(long, int)}, methods of this class, then its interrupt status will be cleared and it will receive an { InterruptedException}.
也就是:处于阻塞的线程,即在执行Object对象的wait()、wait(long)、wait(long, int),或者线程类的join()、join(long)、join(long, int)、sleep(long)、sleep(long,int)方法后线程的状态,当线程调用interrupt()方法后,这些方法将抛出InterruptedException异常,并清空线程的中断状态。
比如下面的例子会中断两次,第一次sleep方法收到中断信号后抛出了InterruptedException,捕获异常后中断状态清空,然后继续执行下一次:
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(){ @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("interrupt"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); thread.interrupt(); Thread.sleep(5000); thread.interrupt(); }
而下面这个例子则会一直执行,不会被打断:
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(){ @Override public void run() { while (true) System.out.println("interrupt"); } }; thread.start(); thread.interrupt(); }
interrupted与isInterrupted方法啥区别?
Thread类并没有提供单独清除中断状态的方法,所以有两种方式来达到此目的:
线程中断有哪些实际应用?
线程中断的几个实际应用场景:
以上就是聊聊Java 中的线程中断的详细内容,更多关于Java 线程中断的资料请关注呐喊教程其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。