JUC并发相关

21. 并发终结之线程interrupt

2020-09-24  本文已影响0人  涣涣虚心0215

中断Interrupt可被看做一个线程(发起线程)发送给另外一个线程(目标线程)的一种指示,表示发起线程希望目标线程停止其执行的操作。但是中断仅仅是个诉求,是否满足取决于目标线程,目标线程可能满足这个诉求,或者也可能不理会这个诉求。
Java里每个线程都维护了一个中断标记(boolean)值用于表示线程是否收到了中断,目标线程可以通过Thread.currentThread().isInterrupted()调用来获取该线程的中断标记值,也可以通过Thread.interrupted()来获取并重置(清空)中断标记值(interrupted()方法会获取中断标记值,且将当前线程的中断标记蛇者成false),interrupt()方法则是将目标线程的中断标记值设置成true。

中断相关方法
    //isInterrupted方法一般有目标线程调用,检查当前线程是否被中断
    //ClearInterrupted设的是false,意思就是不会清除中断状态
    public boolean isInterrupted() {
        return isInterrupted(false);
    }
    //Interrupted方法就是ClearInterrupted设为true,那么中断标记位会被重置
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
    //该方法是native方法,由底层实现
    //如果ClearInterrupted设为true,
    //    那么如果当前线程被中断,调用该方法会返回true,返回之后会重置中断标记位
    private native boolean isInterrupted(boolean ClearInterrupted);

    //调用者线程会设置中断标记位为true,
    //如果当前线程被阻塞了,比如wait(), join(), sleep()等方法,
    //    那么调用该方法会导致中断标记位被重置,且抛出InterruptedException
    public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

上面可以看到中断涉及到的方法,那么Interrupt方法对目标线程的影响,具体还要看目标线程对中断的响应。

响应方式

1.无影响,即目标线程无法对中断进行相应,比如InputStream.read(),ReentrantLock.lock()以及申请内部锁等阻塞方法就属于这种类型。
2.取消任务的运行,即目标线程在侦测到中断那一刻所执行的任务被取消(终止),不影响目标线程处理其他任务。
3.工作者线程停止,即目标线程的状态变更为TERMINATED。
在Java里许多阻塞方法对中断的响应方式都是抛出InterruptedException。

方法 为响应中断而抛出的异常
Object.wait()/wait(long)/wait(long, int) InterruptedException
Thread.sleep(long)/sleep(long, int) InterruptedException
Thread.join()/join(long)/join(long, int) InterruptedException
BlockingQueue.take()/put(E) InterruptedException
Lock.lockInterruptibly() InterruptedException
CountDownLatch.await()/await(long, int) InterruptedException
CyclicBarrier.await() InterruptedException
Exchanger.exchange(V) InterruptedException
InterruptibleChannel ClosedByInterruptException

像上面提到的IO阻塞,以及ReentrantLock.lock()都是不响应中断的,意思就是调用Interrupt()方法,没什么作用。
而ReentrantLock.lockInterruptibly()就是可以响应中断的,能够响应中断的方法通常在执行阻塞操作前判断中断标志,如为true,则抛出InterruptedException。

public void lockInterruptibly() throws InterruptedException {
   sync.acquireInterruptibly(1);
}
public final void acquireInterruptibly(int arg)
     throws InterruptedException {
   // 在进入阻塞之前先检查当前线程是不是被中断了,如果是,则抛出InterruptedException,
   // 同时重置中断标记位
   if (Thread.interrupted())
       throw new InterruptedException();
   if (!tryAcquire(arg))
       doAcquireInterruptibly(arg);
}   

此外需要小心的是,如果在while循环里捕捉了InterruptedException,我们需要重新设置中断标记位,因为Interrupted()方法会重置中断标记位。当然更简单的方式就是在while循环外捕捉InterruptedException

//正常的case,while循环判断当前线程是否被中断,如果被中断则结束线程。
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("-----");
            }
        }, "Thread1");
        thread.start();
        Thread.sleep(100);
        thread.interrupt();
    }
}
-----------------------------
//如果在while循环里我们进入了阻塞方法,在被中断的时候抛出了InterruptedException
//可以看到但因Interrupted结果已经重置回false了,线程仍然继续运行。
// 需要当前线程在Interrupt自己,重新设置中断标记位为true才能终止线程。
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("-----");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("interrupted: "+Thread.currentThread().isInterrupted());
                    //需要重新中断当前线程,即重新设置中断标记位。
                    Thread.currentThread().interrupt();
                }
            }
        }, "Thread1");
        thread.start();
        Thread.sleep(100);
        thread.interrupt();
    }
}
-----
interrupted: false
-----
-----
-----
-----
上一篇 下一篇

猜你喜欢

热点阅读