Two-Phase Termination
* 後片付けしてから、おやすみなさい (スレッドの処理をメインの処理と終了処理に分けて、安全にスレッドを終了させる)
特徴
* 終了要求メソッドを用意し、そのメソッド内で「終了用フラグ」と「interruptメソッド」を用いて 終了要求を検知し、終了させるスレッド自身が自分で終了処理を行う。
補足:interrupt
* interrupt() : 休止中のスレッドに割り込みを入れるメソッド
関連記事
http://blogs.yahoo.co.jp/dk521123/32058018.htmlサンプル
Main.java
public class Main { public static void main(String[] args) { System.out.println("Main - Start"); TerminatableThread thread = new TerminatableThread(); thread.start(); try { Thread.sleep(5000); // 終了要求をコール thread.shutdownRequest(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main - End"); } }
TerminatableThread.java
import java.util.concurrent.atomic.AtomicBoolean; public class TerminatableThread extends Thread { private long counter = 0; private AtomicBoolean canShutdown = new AtomicBoolean(false); // 終了要求 public void shutdownRequest() { this.canShutdown.set(true); this.interrupt(); } // 終了要求が出されたかどうか? public boolean isShutdownRequested() { return this.canShutdown.get(); } public final void run() { try { while (!this.isShutdownRequested()) { this.doWork(); } } catch (InterruptedException e) { } finally { this.doShutdown(); } } private void doWork() throws InterruptedException { this.counter++; System.out.println("counter = " + this.counter); Thread.sleep(500); } private void doShutdown() { System.out.println("ShutDown counter = " + this.counter); } }
参考文献
http://d.hatena.ne.jp/tubaki56/20111008/1318073594http://blog.livedoor.jp/kosuke_pg/archives/51774038.html
http://pgcafe.moo.jp/JAVA/thread/main_9.htm