码迷,mamicode.com
首页 > 编程语言 > 详细

中断线程

时间:2016-06-27 13:53:24      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

当对一个线程调用interrupt方法时,线程的中断状态将被置位。这是每一个线程都具有的boolean标志。

interrupt

中断线程。

1 public void interrupt()

 

测试当前线程是否已经中断。

interrupted:

1 public static boolean interrupted()

  线程的中断状态 由该方法清除。

测试线程是否已经中断。

isInterrupted:

1 public boolean isInterrupted()

 线程的中断状态 不受该方法的影响。

 

注释:

1.在catch子句中调用Thread.currentThread().interrupt()来设置中断状态。于是,调用者可以对其进行检测。

1 void mySubTask()
2 {
3 ...
4   try{sleep(delay);}
5 catch(InterruptedException e){Thread.currentThread().interrupt();}
6 ...  
7 }

或者,更好的选择是,用throws InterruptedException标记方法,不采用try语句块捕获异常。于是,调用者(或者,最终的run方法)可以捕获这一异常。

1 void mySubTask() throws InterruptException
2 {
3 ...
4 sleep(delay);
5 ...
6 }

 

中断线程

标签:

原文地址:http://www.cnblogs.com/linst/p/5619894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!