线程中实现不可中断的任务

1. 对线程中断操作的理解

并不会真正地中断一个正在运行的线程,而只是发出中断请求,然后由线程在下一个合适的时刻中断自己。

调用interrupt并不意味着立即停止目标线程正在进行的工作,而只是传递了请求中断的消息。

public class Thread {
    /**interrupt方法能中断目标线程*/
    public void interrupt(){....}
    /**而isInterrupted方法能返回目标线程的中断状态*/
    public boolean isInterrupted() {...}
    /**静态的interrupted方法将清除当前线程的中断状态,并返回它之前的值。清楚中断的唯一方法*/
    public static boolean interrupted() {...}
}

1.1 阻塞库的中断方法

阻塞库方法,例如 Thread.sleep和Object.wait等。都会检查线程何时中断,并且在发现中断时提前返回。它们在响应中断时执行的操作包括:清楚中断状态、抛出InterruptedException,表示阻塞操作由于中断而提前结束。

2.中断发生时继续执行任务,直到完成。

public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException {
   boolean interrupted = false;
   try {
     /**等待任务直到完成*/
     while (true) {
       try {
         return future.get();
       } catch (InterruptedException e) {
         interrupted = true;
       }
     }
   } finally {
     if (interrupted) {
       /**线程中断*/
       Thread.currentThread().interrupt();
     }
   }
 }

猜你喜欢

转载自blog.csdn.net/ai_xiangjuan/article/details/80471335