如何正確停止線程
關於如何正確停止線程,這篇文章(how to stop thread)給出了一個很好的答案, 總結起來就下面3點(在停止線程時):
1. 使用violate boolean變數來標識線程是否停止
2. 停止線程時,需要調用停止線程的interrupt()方法,因為線程有可能在wait()或sleep(), 提高停止線程的即時性
3. 對於blocking IO的處理,盡量使用InterruptibleChannel來代替blocking IO
核心如下:
If you are writing your own small thread then you should follow the following example code.
private volatile Thread myThread; public void stopMyThread() { Thread tmpThread = myThread; myThread = null; if (tmpThread != null) { tmpThread.interrupt(); } } public void run() { if (myThread == null) { return; // stopped before started. } try { // all the run() method's code goes here ... // do some work Thread.yield(); // let another thread have some time perhaps to stop this one. if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("Stopped by ifInterruptedStop()"); } // do some more work ... } catch (Throwable t) { // log/handle all errors here } }