美文网首页
Thread.interrupted和Thread.interr

Thread.interrupted和Thread.interr

作者: 仩渧哋寵 | 来源:发表于2021-02-01 13:25 被阅读0次

interrupt —— 当其他线程通过调用当前线程的interrupt方法,表示向当前线程打个招呼,告诉他可以中断线程的执行了,至于什么时候中断,取决于当前线程自己

@Slf4j
public class InterruptDemo {

  private static int i;
    // while 情况下 interrupt 执行有意义
    //线程处于阻塞状态下的情况下(中断才有意义)
  // 阻塞状态: thread.join  wait  thread.sleep  (从阻塞中唤醒抛出一个异常来中断线程)
  
  public static void main(String[] args) {
    Thread thread = new Thread(()->{
      //Thread.currentThread().isInterrupted() 默认是false
      //判断中断标识
      while (!Thread.currentThread().isInterrupted()){
        log.info("I: "+i);
        i++;
        log.info("I: "+i);
      }
    });
    thread.start();
    thread.interrupt();//中断(友好)

  }
}

Thread.interrupted() 对设置中断标识的线程复位,并且返回当前的中断状态

 /**
   *   Thread.interrupted(); 对设置中断标识的线程复位,并且返回当前的中断状态
   * @throws InterruptedException
   */
  public void exp3() throws InterruptedException {
      Thread thread = new Thread(()->{
        while (true){
          if (Thread.currentThread().isInterrupted()){
            log.info("------"+Thread.currentThread().isInterrupted());
            Thread.interrupted();
            log.info("-======+=="+Thread.currentThread().isInterrupted());
          }
        }
      });
      thread.start();
    TimeUnit.SECONDS.sleep(11);
    thread.interrupt();
  }

简单的理解就是 thread.interrupt();和Thread.interrupted(); 这两个就是一个线程的开关, thread.interrupt()就是将一个线程关闭,而Thread.interrupted()就是将受到thread.interrupt()作用的线程给打开阻止其关闭。

相关文章

网友评论

      本文标题:Thread.interrupted和Thread.interr

      本文链接:https://www.haomeiwen.com/subject/ojrjtltx.html