线程的中断 - Interrupts

Interrupt ?

An interrupt is an indication to a thread that it should stop what it is doing and do something else.html

中断(interupt)是一个指示,指示一个线程中止正在作的事情,并作一些其余的事情。java

咱们一般使用 中断 去终止线程oracle

如何中断线程 ?

调用 interrupt(),向线程发送 interrupt 指示。this

若是一个线程内,频繁的调用一个能够 throw InterruptedException 的方法,在接收到 interrupt 指示时,抛出 InterruptedException 。只须要 catch 该异常,并 return,便可退出 run 方法 —— 即终止了线程。线程

for (int i = 0; i < importantInfo.length; i++) {
    // Pause for 4 seconds
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        return;
    }
    // Print a message
    System.out.println(importantInfo[i]);
}

Thread 的不少方法均可以 throw InterruptedException,好比 Thread.sleep 方法。当获取到 interrupt 指示时,这些方法将抛出异常。捕获这个异常,并 return ,便可中断线程。code

若是一个线程会运行很长时间,且没有调用任何能够 throw InterruptedException 的方法,怎么办?必须按期运行 Thread.interrupted 方法,当获取 interrupt 指令时返回 truehtm

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

若是项目比较复杂的话,throw new InterruptedException 更有意义get

if (Thread.interrupted()) {
    throw new InterruptedException();
}

中断状态标志 - The Interrupt Status Flag

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.input

interrupt 机制的实现,使用了一个内部的flag,用于标识 interrupt status 。it

调用 静态方法 Thread.interrupted(用于检查当前 Thread 是否 interrupt),interrupt status 会被清除。
调用 非静态方法 isInterrupted(用于一个 Thread 查询另外一个 Thread 是否 interrupt),不会清除 interrupt status。

参考资料

相关文章
相关标签/搜索