特性
[Interrupt为什么有时候有用,有时候没用呢。]
- Interrupt设置一个线程为中断状态
- Interrupt操作的线程处于sleep,wait,join 阻塞等状态的时候,会抛出一个InterruptedException
- Interrupt操作的线程在可中断通道上因调用某个阻塞的 I/O 操作(serverSocketChannel. accept()、socketChannel.connect、socketChannel.open、
socketChannel.read、socketChannel.write、fileChannel.read、fileChannel.write),会抛出一个ClosedByInterruptException
- 我们通过try/catch捕获后则可进行return/break/throw new XXException()等方式返回来销毁或结束线程
下面来看例子
第一个例子解释了为什么Interrupt执行后线程依然没有中断
后两个例子针对I/O阻塞以及sleep等状态进行了中断操作
例子1.
/**
* 常规interrupt
*
* @author Allen
* @date 2017年2月21日
*
*/
public class e1 implements Runnable {
public static void main(String[] args) {
e1 nm=new e1();
Thread thread = new Thread(nm);
System.out.println("躁起来修电脑去");
System.out.println("interrupt state = " + thread.isInterrupted());
thread.start();
nm.sleep(500);
thread.interrupt();
System.out.println("别修复了,世界末日了");
System.out.println("interrupt state = " + thread.isInterrupted());
}
public void run() {
System.out.println("开始修复电脑");
for (int i = 10; i <= 100; i += 10) {
if(Thread.interrupted())
System.out.println("~~别烦我我得修完了");
System.out.println("修复进度" + i + "%");
sleep(200);
}
System.out.println("修复完毕");
}
/**
* 自己写个sleep条件循环为了禁止Interrupt对Thread.sleep(x)时的异常抛出
* @param step
* @author Allen
* @date 2017年2月21日
*/
private void sleep(int step) {
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < step)) {
}
}
}
执行结果
躁起来