三、中断机制:InterruptedException

多线程中某些任务可能会被执行很耗时的操作,从而导致该线程处于阻塞的状态。在某些情况下,我们想取消这个线程的操作。这就是中断机制。

中断机制的设计原理也很简单,就是在Thread中设置一个标志位。

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();
}

关于中断机制,有一个很经典的问题:任何线程都可以被中断吗?

答案是No。举个例子:

    public static void main(String[] args) throws InterruptedException {
        Thread newThread = new Thread(() -> {
            try {
                int i = 0;
                while (true) {
                    doSomething();
                    i++;
                }
            } catch (InterruptedException e) {
                System.out.println("this thread are interrupted");
                e.printStackTrace();
            }
        });
        newThread.start();

        Thread.sleep(5000);
        newThread.interrupt();
    }

    private static void doSomething() throws InterruptedException {
    }

你会发现这个新线程不会被中断。这是因为一个线程是否被中断,取决它自己的执行策略。一般来说,jdk中耗时比较久的方法,都会抛出InterruptedException异常,以此来响应线程中断。

3、中断操作的执行建议

  • Thread处理InterruptedException的操作:设置当前线程的标志位

results matching ""

    No results matching ""