线程取消与关闭

Java没有安全的抢占方法来停止线程,只有协作式的机制,使代码遵循一种协商好的协议来提前结束线程。

其中一种协作机制是通过设置标志(已请求取消),任务将定期查看该标志,如果设置了该标志,则任务提前结束。

例如我们可以通过volatile类型域(关于volatitle类型域的特点和作用本篇不做介绍,不了解的同学可以自行搜索)来取消,设置变量private volatile boolean cancelled = false;
在任务中循环判断cancelled来跳出循环

 private volatile boolean cancelled = false;
 while(!cancelled){
    System.out.println(" queue.put 1");
    queue.put(p = p.nextProbablePrime());
    System.out.println(" queue.put 2");
}

public void cancel(){
//      interrupt();
    cancelled = true;
    System.out.println(" cancel ");
}

但如果使用这个方法的任务中调用了阻塞方法,可能会因为阻塞而存在代码永远不会执行到检查标志位的地方,因此永远不会结束(一直卡在阻塞位置)
LOG如下:
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
consume value = 2
cancel

所以保险情况是通过中断来取消

完整代码如下

package com.thread.test.interrupt;

import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import static java.util.concurrent.TimeUnit.SECONDS;

public class PrimeProducer extends Thread {
    private final BlockingQueue<BigInteger> queue;
    private volatile boolean cancelled = false;
    public PrimeProducer(BlockingQueue<BigInteger> queue) {
        // TODO Auto-generated constructor stub
        this.queue = queue;
    }
    
    public void run() {
        try{
            BigInteger p = BigInteger.ONE;
//          // volatile类型域
//          while(!cancelled){
//              System.out.println(" queue.put 1");
//              queue.put(p = p.nextProbablePrime());
//              System.out.println(" queue.put 2");
//          }
            
//          while(!Thread.currentThread().isInterrupted()){
//              System.out.println(" queue.put 1");
//              queue.put(p = p.nextProbablePrime());
//              System.out.println(" queue.put 2");
//          }
            while(true){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println(" isInterrupted ");
                    break;
                }
                System.out.println(" queue.put 1");
                queue.put(p = p.nextProbablePrime());
                System.out.println(" queue.put 2");
            }
        }catch(InterruptedException e){
            System.out.println(" InterruptedException e");
        }
    }
    
    public void cancel(){
        interrupt();
//      cancelled = true;
        System.out.println(" cancel ");
    }
    
    public static boolean needMroePrime(int count){
        if(count >= 1){
            return false;
        }else{
            return true;
        }
    }
    
    public static void consume(BigInteger value){
        System.out.println(" consume value = "+value);
    }
    
    public static void main(String[] args) {
        final BlockingQueue<BigInteger> prime = new ArrayBlockingQueue<BigInteger>(3);
        PrimeProducer producer = new PrimeProducer(prime);
        producer.start();
        int count = 0;
        try{
            SECONDS.sleep(1);
            while(needMroePrime(count)){
                count++;
                consume(prime.take());
            }
        }catch(InterruptedException e){
            
        }finally{
            producer.cancel();
        }
    }
    
    
}

程序运行结果示例:
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
consume value = 2
cancel
InterruptedException e

从LOG执行情况我们可以看到,线程虽然还是阻塞在put方法中,但还是通过抛出异常而退出,进一步查看源码我们可以发现在BlockingQueue的put方法中会抛出InterruptedException异常,并注明 InterruptedException if interrupted while waiting
(继续深入源码可以发现阻塞实际是一个while循环不断执行,再循环中会判断Thread.interrupted(),中断则抛出InterruptedException, AbstractQueuedSynchronizer$ConditionObject)
另外一些阻塞库方法,例如Thread.sleep和Object.wait等,都会检查线程何时中断,并再发现中断时提前返回,清除中断状态并抛出异常。

我们得出如下结论:

通常,中断是实现取消最合理的方式

其他中断线程的方法:

Thread.stop(),此方法由于严重的缺陷以及被废弃,非常不建议使用,具体原因大家可自行查找

为什么要使用抛出InterruptedException的方式:

  1. 首先,我们再次回顾一下线程取消的概念,是让任务提前结束,提前结束的意思可以理解线程Run方法中没有代码需要执行
  2. 线程中断本质上也是通过判断标志位进而抛出InterruptedException异常,抛出异常后线程实际上还没有退出,捕获异常之后如果直接不处理或者在Run方法中直接return则线程就被取消了,如果还有一些操作(比如例子中的打印日志),代码还是会执行,这里可以做一些中断策略的设计,一般我们会用来复位一些标记位,做一些资源释放的逻辑。
  3. 如果不使用抛出异常的方式会怎么样?比如在循环中我们可以通过break提前退出,再方法函数中我们可以通过return提前退出,但异常更好,异常可以不断向上抛出(避免多个函数嵌套如果不用异常则需要不停return),只有在捕获的地方进行处理(代码逻辑会更清晰),甚至可以处理之后继续向上抛出,可以非常灵活的使用,这里可以参考这篇文章 https://www.cnblogs.com/greta/p/5624839.html

附录
Thread中的中断方法说明

public class Thread{
  public void interrupt(){...}
  public boolean isInterrupted(){...}
  public static boolean interrupted(){
    return currentThread().isInterrupted(true);
  }
  // 确定线程是否被中断,根据ClearInterrupted值决定是否重置
  private native boolean isInterrupted(boolean ClearInterrupted);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容