线程中断捕捉异常后,后面的代码依然会捕捉到异常

牧之~ 2018-03-06 08:19:40

public static void main(String[] args)
{
ExecutorService executor = Executors.newSingleThreadExecutor();

executor.execute(new Runnable()
{
@Override
public void run()
{
try
{
TimeUnit.SECONDS.sleep(10);
System.out.println("first run over");
}
catch (InterruptedException e)
{
System.out.println("first interrupted!!!");
}

System.out.println("----分割线执行----");

try
{
TimeUnit.SECONDS.sleep(5);
System.out.println("second run over");

}
catch (InterruptedException e)
{
System.out.println("second interrupted!!!");

}
}
});

executor.shutdownNow();

}

以上如何解释?各种理论都是说的只会中断一次。

运行结果

first interrupted!!!
----分割线执行----
second interrupted!!!

如果不使用线程池发现是没有问题的。



public class HH
{

public static void main(String[] args) throws InterruptedException
{
ThreadA ta = new ThreadA();
ta.setName("ThreadA");
ta.start();
Thread.sleep(2000);
System.out.println(ta.getName() + "正在被中断...");
ta.interrupt();
System.out.println("ta.isInterrupted()=" + ta.isInterrupted());

}
}

class ThreadA extends Thread
{
int count = 0;

public void run()
{
System.out.println(getName() + "将要运行...");

while (!this.isInterrupted())
{
try
{
Thread.sleep(400);

}
catch (InterruptedException e)
{
System.out.println(getName() + "****从阻塞中退出...");

System.out.println("this.isInterrupted()=" + this.isInterrupted());
}

try
{

System.out.println(getName() + "运行中" + count++);

Thread.sleep(400);
}
catch (InterruptedException e)
{
System.out.println(getName() + "---------从阻塞中退出...");

System.out.println("this.isInterrupted()=" + this.isInterrupted());
}

}


System.out.println(getName() + "已经终止!");
}
}
...全文
619 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
醉-风尘Oo 2018-04-04
  • 打赏
  • 举报
回复
捕获异常后 会清除interrupt状态
牧之~ 2018-03-27
  • 打赏
  • 举报
回复
引用 3 楼 xiongdejun 的回复:
http://blog.csdn.net/canot/article/details/51087772 你理解下 ta.interrupt();就懂了
理解了还是这样,问题是二楼把代码拷贝过去和我的执行结果竟然不一致,这作何解释?
xiongdejun 2018-03-07
  • 打赏
  • 举报
回复
http://blog.csdn.net/canot/article/details/51087772 你理解下 ta.interrupt();就懂了
define_us 2018-03-07
  • 打赏
  • 举报
回复
神奇了
牧之~ 2018-03-06
  • 打赏
  • 举报
回复
例子二执行结果

ThreadA将要运行...
ThreadA运行中0
ThreadA运行中1
ThreadA正在被中断...
ta.isInterrupted()=true
ThreadA****从阻塞中退出...
this.isInterrupted()=false
ThreadA运行中2
ThreadA运行中3
ThreadA运行中4
ThreadA运行中5
ThreadA运行中6
ThreadA运行中7
ThreadA运行中8
ThreadA运行中9
...

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧