2

如何安全中断一个正在运行的线程?

 1 month ago
source link: https://www.v2ex.com/t/1034322
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Java

如何安全中断一个正在运行的线程?

  dvsusan123 · 12 小时 35 分钟前 · 1394 次点击
线程是操作系统进行运算调度的最小单位,所以线程是系统级别的概念。

在 Java 中,可以使用 Thread.interrupt()方法安全中断一个正在运行的线程。

其中 Thread.interrupt()方法用于设置线程的中断状态为"中断"。它并不会直接终止线程的执行,而是给线程一个中断信号。

在执行线程的代码中,可以通过检查 Thread.interrupted()或 Thread.currentThread().isInterrupted()方法来判断线程是否被中断。

如果线程被中断,应根据具体情况决定如何处理中断。可以选择抛出 InterruptedException 异常、恢复线程到一个安全的状态,或者终止线程的执行。

如果线程处于等待状态(如 Thread.sleep()、Object.wait()、Thread.join()等),那么线程会立即从等待状态返回,并且 InterruptedException 异常会被抛出。

使用 Thread.interrupt()方法可以安全地中断一个正在运行的线程,并通过 Thread.currentThread().isInterrupted()方法检查线程的中断状态。在处理中断时,可以选择抛出 InterruptedException 异常、恢复线程到安全状态或者终止线程的执行。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK