两阶段终止模式 Two Phase Termination

在一个线程T1中如何“优雅”终止线程T23这里的【优雅】指的是给T2一个料理后事的机会.

错误思路

1.使用线程对象的stop()方法停止线程

stop方法会真正杀死线程,如果这时线程锁住了共享资源,那么当它被杀死后就 再也没有机会释放锁,其它线程将永远无法获取锁

2.使用 System.exit(int)方法停止线程

目的仅是停止一个线程,但这种做法会让整个程序都停止

两阶段终止模式流程

image.png

实现代码

  1. package com.yuanzi.Interrupt;
  2. import lombok.extern.slf4j.Slf4j;
  3. /**
  4. * @program: practice
  5. * @description: 两阶段终止模式
  6. * @author: yuanzi
  7. * @create: 2021-06-09 02:13
  8. **/
  9. @Slf4j(topic = "c.TwoPhaseTemination")
  10. public class TwoPhaseTemination {
  11. private Thread monitor;
  12. //启动监控线程
  13. public void start() {
  14. monitor = new Thread(() -> {
  15. while (true) {
  16. Thread currentThread = Thread.currentThread();
  17. if (currentThread.isInterrupted()) {
  18. log.debug("料理后事");
  19. break;
  20. }
  21. try {
  22. Thread.sleep(1000); //情况1
  23. log.debug("执行监控记录"); //情况2
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. //重新设置打断标记
  27. currentThread.interrupt();
  28. }
  29. }
  30. });
  31. monitor.start();
  32. }
  33. //停止监控线程
  34. public void stop() {
  35. monitor.interrupt();
  36. }
  37. public static void main(String[] args) throws InterruptedException {
  38. TwoPhaseTemination tpt = new TwoPhaseTemination();
  39. tpt.start();
  40. Thread.sleep(5000);
  41. tpt.stop();
  42. }
  43. }

运行结果
image.png