一、LockSapport与线程中断
1、线程中断机制
1.什么是中断机制
- 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以Thread.stop()、Thread.suspend()、等都已经废弃。
- 在java中没有办法立即停止一条线程,然而停止线程却显的尤为重要,如取消一个耗时操作。因此,java提供了一种用于停止线程的协商机制——中断,即为中断标识协商机制
- 中断只是一种协作协商机制,java没有给中断增加任何语法,中断的过程完全需要程序员自己实现。若要中断一个线程,你需要手动调用该线程的interrupt方法,该方法也仅仅是将线程对象的中断标识设为true。接着你需要自己写代码检测当前线程的标识位,如果位true,表示别的线程请求这条线程中断。
- 每个线程对象中都有一个中断标识位,用于表示线程是否被中断,该标识位true表示中断,为false表示未中断;通过调用线程对象的interrupt方法,将该线程标识设为true;可以在别的线程中调用,也可以在自己线程调用。
2、中断机制的三大方法
-
public void interrupt()
实例方法interrupt()仅仅是设置线程的中断状态为true,发起一个协商不会立刻停止线程
-
public void isInterrupted()
判断当前线程是否被中断
-
public static void interrupted()
判断线程是否被中断清除当前中断状态
- 返回当前线程的中断状态,测试当前线程是否已被中断
- 将当前线程的中断状态清零并重新设为false,清除线程的中断状态
3、面试题中断机制考点
1、如何停止中断运行中的线程?
-
通过volatile变量实现
public static volatile boolean interrupt = false; public static void method1() { new Thread(() -> { while (true) { if (interrupt) { System.out.println("中断状态程序停止" + interrupt); break; } System.out.println("Hello volatile"); } }).start(); try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } interrupt = true; System.out.println(Thread.currentThread().getName() + "执行完毕"); }
-
通过AtomicBoolean
public static AtomicBoolean isInterrupt = new AtomicBoolean(false);//原子Boolean 用于操作多线程 public static void method2() { new Thread(() -> { while (true) { if (isInterrupt.get()) { System.out.println("中断状态程序停止" + interrupt); break; } System.out.println("Hello AtomicBoolean"); } }).start(); try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } // interrupt = true; isInterrupt.set(true); System.out.println(Thread.currentThread().getName() + "执行完毕"); }