在本博文的一篇如何正确的关闭一个线程
一文中讲解了如何利用interrupt机制来中断一个线程,这篇文章当时确实花了一些精力的总结,不过都是15年末的事情了,现在是2017年2月份,经过一年的时间,决定重新写一篇完善的关于线程中断的文章。
下面简单的举例情况:
比如我们会启动多个线程做同一件事,比如抢12306的火车票,我们可能开启多个线程从多个渠道买火车票,只要有一个渠道买到了,我们会通知取消其他渠道。这个时候需要关闭其他线程很多线程的运行模式是死循环,比如在生产者/消费者模式中,消费者主体就是一个死循环,它不停的从队列中接受任务,执行任务,在停止程序时,我们需要一种”优雅”的方法以关闭该线程在一些场景中,比如从第三方服务器查询一个结果,我们希望在限定的时间内得到结果,如果得不到,我们会希望取消该任务。总之,很多情况下我们都有关闭一个线程的需求,那么如何正确的关闭一个线程就是我们要研究的事情,这个事情在上一篇文章中已经讨论过了,这里不在赘述。Thread.STOP()
之类的api会造成一些不可预知的bug,所以很早便DePRecated
了,真要纠结为什么请看这边文章为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?
Thread类定义了如下关于中断的方法:
API | 作用 |
---|---|
public static boolean interrupted | 就是返回对应线程的中断标志位是否为true返回当前线程的中断标志位是否为true,但它还有一个重要的副作用,就是清空中断标志位,也就是说,连续两次调用interrupted(),第一次返回的结果为true,第二次一般就是false (除非同时又发生了一次中断)。 |
public boolean isInterrupted() | 就是返回对应线程的中断标志位是否为true |
public void interrupt() | 表示中断对应的线程 |
如果线程在运行中,interrupt()只是会设置线程的中断标志位,没有任何其它作用。线程应该在运行过程中合适的位置检查中断标志位,比如说,如果主体代码是一个循环,可以在循环开始处进行检查,如下所示:
123456789101112131415 | public class InterruptRunnableDemo extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { // ... 单次循环代码 } System.out.println("done "); } public static void main(String[] args) throws InterruptedException { Thread thread = new InterruptRunnableDemo(); thread.start(); Thread.sleep(1000); thread.interrupt(); }} |
线程执行如下方法会进入WAITING状态:
12 | public final void join() throws InterruptedExceptionpublic final void wait() throws InterruptedException |
执行如下方法会进入TIMED_WAITING状态:
123 | public final native void wait(long timeout) throws InterruptedException;public static native void sleep(long millis) throws InterruptedException;public final synchronized void join(long millis) throws InterruptedException |
在这些状态时,对线程对象调用interrupt()会使得该线程抛出InterruptedException,需要注意的是,抛出异常后,中断标志位会被清空(线程的中断标志位会由true重置为false,因为线程为了处理异常已经重新处于就绪状态。),而不是被设置。比如说,执行如下代码:
1234567891011121314151617 | Thread t = new Thread (){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { //exception被捕获,但是为输出为false 因为标志位会被清空 System.out.println(isInterrupted()); } } };t.start();try { Thread.sleep(100);} catch (InterruptedException e) {}t.interrupt();//置为true |
InterruptedException是一个受检异常,线程必须进行处理。我们在异常处理中介绍过,处理异常的基本思路是,如果你知道怎么处理,就进行处理,如果不知道,就应该向上传递,通常情况下,你不应该做的是,捕获异常然后忽略。
捕获到InterruptedException,通常表示希望结束该线程,线程大概有两种处理方式:
向上传递该异常,这使得该方法也变成了一个可中断的方法,需要调用者进行处理有些情况,不能向上传递异常,比如Thread的run方法,它的声明是固定的,不能抛出任何受检异常,这时,应该捕获异常,进行合适的清理操作,清理后,一般应该调用Thread的interrupt方法设置中断标志位,使得其他代码有办法知道它发生了中断第一种方式的示例代码如下:
12345 | //抛出中断异常,由调用者捕获public void interruptibleMethod() throws InterruptedException{ // ... 包含wait, join 或 sleep 方法 Thread.sleep(1000);} |
第二种方式的示例代码如下:
123456789101112131415161718192021222324252627 | public class InterruptWaitingDemo extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { // 模拟任务代码 Thread.sleep(2000); } catch (InterruptedException e) { // ... 清理操作 System.out.println(isInterrupted());//false // 重设中断标志位为true Thread.currentThread().interrupt(); } } System.out.println(isInterrupted());//true } public static void main(String[] args) { InterruptWaitingDemo thread = new InterruptWaitingDemo(); thread.start(); try { Thread.sleep(100); } catch (InterruptedException e) { } thread.interrupt(); }} |
如果线程在等待锁,对线程对象调用interrupt()只是会设置线程的中断标志位,线程依然会处于BLOCKED状态,也就是说,interrupt()并不能使一个在等待锁的线程真正”中断”。我们看段代码:
1234567891011121314151617181920212223242526 | public class InterruptWaitingDemo extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { // 模拟任务代码 Thread.sleep(2000); } catch (InterruptedException e) { // ... 清理操作 // 重设中断标志位 Thread.currentThread().interrupt(); } } System.out.println(isInterrupted()); } public static void main(String[] args) { InterruptWaitingDemo thread = new InterruptWaitingDemo(); thread.start(); try { Thread.sleep(100); } catch (InterruptedException e) { } thread.interrupt(); }} |
BLOCKED如果线程在等待锁,对线程对象调用interrupt()只是会设置线程的中断标志位,线程依然会处于BLOCKED状态,也就是说,interrupt()并不能使一个在等待锁的线程真正”中断”。我们看段代码:
1234567891011121314151617181920212223242526272829 | public class InterruptSynchronizedDemo { private static Object lock = new Object();//monitor private static class A extends Thread { @Override public void run() { //等待lock锁 synchronized (lock) { //等待标志位被置为true while (!Thread.currentThread().isInterrupted()) { } } System.out.println("exit"); } } public static void test() throws InterruptedException { synchronized (lock) {//获取锁 A a = new A(); a.start(); Thread.sleep(1000); //a在等待lock锁,interrupt 无法中断 a.interrupt(); //a线程加入当前线程,等待执行完毕 a.join(); } } public static void main(String[] args) throws InterruptedException { test(); }} |
test方法在持有锁lock的情况下启动线程a,而线程a也去尝试获得锁lock,所以会进入锁等待队列,随后test调用线程a的interrupt方法并等待线程线程a结束,线程a会结束吗?不会,interrupt方法只会设置线程的中断标志,而并不会使它从锁等待队列中出来。
我们稍微修改下代码,去掉test方法中的最后一行a.join,即变为:
123456789 | public static void test() throws InterruptedException { synchronized (lock) { A a = new A(); a.start(); Thread.sleep(1000); a.interrupt(); } //lock锁释放后 A线程重队列中出来} |
这时,程序就会退出。为什么呢?因为主线程不再等待线程a结束,释放锁lock后,线程a会获得锁,然后检测到发生了中断,所以会退出。
在使用synchronized关键字获取锁的过程中不响应中断请求,这是synchronized的局限性。如果这对程序是一个问题,应该使用显式锁,java中的Lock接口,它支持以响应中断的方式获取锁。对于Lock.lock(),可以改用Lock.lockInterruptibly(),可被中断的加锁操作,它可以抛出中断异常。等同于等待时间无限长的Lock.tryLock(long time, TimeUnit unit)。
如果线程尚未启动(NEW),或者已经结束(TERMINATED),则调用interrupt()对它没有任何效果,中断标志位也不会被设置。比如说,以下代码的输出都是false。
12345678910111213141516171819202122 | public class InterruptNotAliveDemo { private static class A extends Thread { @Override public void run() { } } public static void test() throws InterruptedException { A a = new A(); a.interrupt(); System.out.println(a.isInterrupted()); a.start(); Thread.sleep(100); a.interrupt(); System.out.println(a.isInterrupted()); } public static void main(String[] args) throws InterruptedException { test(); }} |
如果线程在等待IO操作,尤其是网络IO,则会有一些特殊的处理,我们没有介绍过网络,这里只是简单介绍下。
实现此InterruptibleChannel接口的通道是可中断的:如果某个线程在可中断通道上因调用某个阻塞的 I/O 操作(常见的操作一般有这些:serverSocketChannel. accept()、socketChannel.connect、socketChannel.open、socketChannel.read、socketChannel.write、fileChannel.read、fileChannel.write)而进入阻塞状态,而另一个线程又调用了该阻塞线程的 interrupt 方法,这将导致该通道被关闭,并且已阻塞线程接将会收到ClosedByInterruptException,并且设置已阻塞线程的中断状态。另外,如果已设置某个线程的中断状态并且它在通道上调用某个阻塞的 I/O 操作,则该通道将关闭并且该线程立即接收到 ClosedByInterruptException;并仍然设置其中断状态。如果线程阻塞于Selector调用,则线程的中断标志位会被设置,同时,阻塞的调用会立即返回。我们重点介绍另一种情况,InputStream的read调用,该操作是不可中断的,如果流中没有数据,read会阻塞 (但线程状态依然是RUNNABLE),且不响应interrupt(),与synchronized类似,调用interrupt()只会设置线程的中断标志,而不会真正”中断”它,我们看段代码
1234567891011121314151617181920212223 | public class InterruptReadDemo { private static class A extends Thread { @Override public void run() { while(!Thread.currentThread().isInterrupted()){ try { System.out.println(System.in.read())//wait input } catch (IOException e) { e.printStackTrace(); } } System.out.println("exit"); } } public static void main(String[] args) throws InterruptedException { A t = new A(); t.start(); Thread.sleep(100); t.interrupt(); }} |
线程t启动后调用System.in.read()从标准输入读入一个字符,不要输入任何字符,我们会看到,调用interrupt()不会中断read(),线程会一直运行。
不过,有一个办法可以中断read()调用,那就是调用流的close方法,我们将代码改为:
12345678910111213141516171819202122232425262728 | public class InterruptReadDemo { private static class A extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { System.out.println(System.in.read()); } catch (IOException e) { e.printStackTrace(); } } System.out.println("exit"); } public void cancel() { try { System.in.close(); } catch (IOException e) { } interrupt(); } } public static void main(String[] args) throws InterruptedException { A t = new A(); t.start(); Thread.sleep(100); t.cancel(); }} |
我们给线程定义了一个cancel方法,在该方法中,调用了流的close方法,同时调用了interrupt方法,这次,程序会输出:
12 | -1exit |
也就是说,调用close方法后,read方法会返回,返回值为-1,表示流结束。
再比如,ExecutorService提供了如下两个关闭方法:
12 | void shutdown();List<Runnable> shutdownNow(); |
Future和ExecutorService的API文档对这些方法都进行了详细说明,这是我们应该学习的方式。
新闻热点
疑难解答