分两段终止。

    啥意思呢?
    就是你想睡觉,但是你憋着一泡屎,不拉出来是睡不着的,那就先拉完屎,然后再去睡觉。

    话糙理不糙,先执行终止处理,再终止线程。

    这就引出了 线程停止的安全性了,都知道不推荐 stop。因为不安全。需要用中断或者信号量去停止线程。我们这个模式就是说的这个。

    发起中断后,Thread.sleep()方法,会接受到这个信号,然后抛出异常。

    1. public class CountupThread extends Thread {
    2. private int counter = 0;
    3. private volatile boolean shtdownRequested = false;
    4. public void shutdownRequest() {
    5. shtdownRequested = true;
    6. interrupt();
    7. }
    8. public boolean isShtdownRequested() {
    9. return shtdownRequested;
    10. }
    11. @Override
    12. public void run() {
    13. super.run();
    14. try {
    15. while (!isShtdownRequested()) {
    16. doWork();
    17. }
    18. } catch (InterruptedException e) {
    19. e.printStackTrace();
    20. } finally {
    21. doShutdowwn();
    22. }
    23. }
    24. private void doShutdowwn() {
    25. System.out.println("doShutdowwn:counter = " + counter);
    26. }
    27. private void doWork() throws InterruptedException {
    28. counter++;
    29. System.out.println("doWork: counter" + counter);
    30. Thread.sleep(500);
    31. }
    32. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. try {
    4. System.out.println("main BEGIN");
    5. CountupThread thread = new CountupThread();
    6. thread.start();
    7. Thread.sleep(10000);
    8. System.out.println("main shutdownRequest");
    9. thread.shutdownRequest();
    10. System.out.println("main :join");
    11. thread.join();
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. }