InterruptedException详解
来源:互联网 发布:文字转音频软件 编辑:程序博客网 时间:2024/05/17 18:47
1.线程为什么会抛出InterruptedException?
假如现在有两个线程1和2;线程1在正常执行,此时线程2调用了线程1的interrupt方法;代码如下:
@RunWith(SpringJUnit4ClassRunner.class)public class SynchronizedTest { @Test public void testSynchronized(){ Thread thread = new Thread(){ public void run(){ System.out.println(Thread.currentThread().getName()+ "线程开始了~"); System.out.println(Thread.currentThread().getName()+ "线程结束了~"); } }; thread.start(); System.out.println("1" + thread.isInterrupted()); thread.interrupt(); System.out.println("2" + thread.isInterrupted()); System.out.println("测试结束"); }}
运行结果如下:
1false
2true
测试结束
Thread-2线程开始了~
Thread-2线程结束了~
然而;如果线程处于wait,sleep,join三个方法时候,则会抛出InterruptedException。我们看下代码
public void testSynchronized(){ Thread thread = new Thread(){ public void run(){ System.out.println(Thread.currentThread().getName()+ "线程开始了~"); try { sleep(1000); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName()+"抛出了InterruptedException"); System.out.println("2" + isInterrupted()); } System.out.println(Thread.currentThread().getName()+ "线程结束了~"); } }; thread.start(); System.out.println("1" + thread.isInterrupted()); thread.interrupt(); System.out.println("测试结束");运行结果如下:
1false
测试结束
Thread-2线程开始了~
Thread-2抛出了InterruptedException
2false
Thread-2线程结束了~
可见:线程抛出了InterruptedException,但是线程的中断状态并没有变成true
2.如何处理InterruptedException?
一般来说,有三种做法:
(1)不做处理,直接抛出
直接抛出并不会影响线程的状态,被中断的线程还是会提前结束中断状态,继续执行
(2)捕获异常,再次调用interrupt方法,将中断状态重新设置为true;Thread.currentThread().interrupt();
这样就保留了线程原有的状态,让线程继续等待下去
(3)捕获异常,不处理;(不推荐)
3.正常运行的线程如何对中断状态做处理
由1我们知道,正常运行的线程在调用了interrupt方法后将中断状态设置为true,但此时线程的执行并未收到影响,如果要对线程的运行采取一些干预措施,则需要使用isInterrupt方法;还有个比较危险的方法 interrrupted(),只清除中断状态
如:if(thread.isInterrupt()){
//do Somethidng
}
阅读全文
0 0
- InterruptedException详解
- InterruptedException
- 处理 InterruptedException
- InterruptedException 异常
- InterruptedException的解读
- InterruptedException的解读
- 怎样处理InterruptedException
- 对InterruptedException的正确处理
- java.lang.InterruptedException
- InterruptedException的解读
- Java线程之InterruptedException
- 如何处理InterruptedException异常
- 遇见InterruptedException异常,怎么办?
- interrupt、interrupted 、isInterrupted、InterruptedException
- Java如何处理InterruptedException?
- Java线程之 InterruptedException 异常
- Java正确处理InterruptedException的方法
- java 线程 stop sleep interruptedException
- indea创建部署gralde项目
- 笨方法学习Python-习题25: 更多更多的练习
- apply()
- 压缩感知重构算法之广义正交匹配追踪(gOMP)
- mycat数据库中间件
- InterruptedException详解
- linux使用sed命令
- 线程中断,interrupt(),interrupted,isInterrupted()
- Git多SSH账号管理
- Linux鸟哥的私房菜-认识系统服务(1)daemon
- linux下FTP服务启动与关闭命令
- SdutAcm-OJ平台 正方形 (java)
- Java设计模式-观察者模式
- 14.(1)Struts2_值栈