分两段终止。
啥意思呢?
就是你想睡觉,但是你憋着一泡屎,不拉出来是睡不着的,那就先拉完屎,然后再去睡觉。
话糙理不糙,先执行终止处理,再终止线程。
这就引出了 线程停止的安全性了,都知道不推荐 stop。因为不安全。需要用中断或者信号量去停止线程。我们这个模式就是说的这个。
发起中断后,Thread.sleep()方法,会接受到这个信号,然后抛出异常。
public class CountupThread extends Thread {private int counter = 0;private volatile boolean shtdownRequested = false;public void shutdownRequest() {shtdownRequested = true;interrupt();}public boolean isShtdownRequested() {return shtdownRequested;}@Overridepublic void run() {super.run();try {while (!isShtdownRequested()) {doWork();}} catch (InterruptedException e) {e.printStackTrace();} finally {doShutdowwn();}}private void doShutdowwn() {System.out.println("doShutdowwn:counter = " + counter);}private void doWork() throws InterruptedException {counter++;System.out.println("doWork: counter" + counter);Thread.sleep(500);}}
public class Main {public static void main(String[] args) {try {System.out.println("main BEGIN");CountupThread thread = new CountupThread();thread.start();Thread.sleep(10000);System.out.println("main shutdownRequest");thread.shutdownRequest();System.out.println("main :join");thread.join();} catch (InterruptedException e) {e.printStackTrace();}}}
