如何关闭一个线程
  • 线程生命周期结束
  • 捕获中断信号关闭线程
  • 异常退出
  • 进程假死

interrupt结束线程

interrupt三个方法

  • void interrupt()
  • static boolean interrupted()
  • boolean isInterrupted()
package concurrency.base.interrupter;

import java.util.concurrent.TimeUnit;

/**
 * @program: algo
 * @description: interrupt
 * @author: bikang
 * @create: 2021-10-05 19:06
 */
public class ThreadInterrupt {

    public static void main(String[] args) throws Exception{

        Thread thread = new Thread(() -> {
            System.out.println("is-interrupt:"+Thread.currentThread().isInterrupted());
            try {
                TimeUnit.MINUTES.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("interrupt ok");
            }
            System.out.println("is-interrupt:"+Thread.currentThread().isInterrupted());
            Thread.interrupted();
            System.out.println("is-interrupt:"+Thread.currentThread().isInterrupted());
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();

        System.out.println("isInterrupted:"+thread.isInterrupted());


    }
}