中断线程的两种方式(isInterrupt和boolean变量)

线程可以通过检查自身是否被中断来进行响应

  • interrupt:通过此方法可以对线程进行中断操作
  • isInterrupted :来判断线程是否被中断
    • 如果线程已结束,即使有过中断操作,调用这个isInterrupted也会返回false
    • 声明InterruptedException异常的方法(例如 Thread.sleep()方法),在抛出异常之前,JVM会先清除该线程的中断标识位,此时调用此isInterrupted也是返回false
  • interrputed:对中断线程进行复位

线程还可以通过设置一个volatile变量来作为中断表示,来判断是否需要停止任务

public class Runner implements Runnable {
    private long i;
    //使用标识位
    private volatile boolean on = true;
    @Override
    public void run() {
        //isInterrupted,查看线程是否被中断
        while (on && !Thread.currentThread().isInterrupted()){
            i++;
        }
        System.out.println("Count i = "+i);
    }
    //对标识位进行操作
    public void cancle(){
        on = false;
    }
}

//中断线程的两种方式,interrupt和boolean变量
public class shutDown {
    public static void main(String[] args) throws Exception{
        Runner one = new Runner();
        //通过Runnable创建线程
        Thread countThread = new Thread(one);
        countThread.start();
        TimeUnit.SECONDS.sleep(1);
        //中断线程
        countThread.interrupt();

        Runner two = new Runner();
        countThread = new Thread(two);
        countThread.start();
        TimeUnit.SECONDS.sleep(1);
        //通过改变标识位中断线程
        two.cancle();
    }
}

以上参考自《Java并发编程艺术》4.2章节

你可能感兴趣的:(并发编程)