多线程设计模式--two-phase termination
2009-09-17 00:00:00 来源:WEB开发网two-phase termination 等待线程执行终止处理再结束线程
Java代码
public class CountupThread extends Thread {
// 计数器的值
private long counter = 0;
// 已经送出终止请求则为true
private volatile boolean shutdownRequested = false;
// 终止请求
public void shutdownRequest() {
shutdownRequested = true;
interrupt();
}
// 判断终求请求是否已经送出
public boolean isShutdownRequested() {
return shutdownRequested;
}
//动作
public final void run() {
try {
while (!shutdownRequested) {
doWork();
}
} catch (InterruptedException e) {
} finally {
doShutdown();
}
}
// 作业
private void doWork() throws InterruptedException {
counter++;
System.out.println("doWork: counter = " + counter);
Thread.sleep(500);
}
// 终止处理
private void doShutdown() {
System.out.println("doShutdown: counter = " + counter);
}
}
测试类
Java代码
public class Main {
public static void main(String[] args) {
System.out.println("main: BEGIN");
try {
CountupThread t = new CountupThread();
t.start();
Thread.sleep(10000);
System.out.println("main: shutdownRequest");
t.shutdownRequest();
System.out.println("main: " + "join");
// 等待该线程终止。
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main: END");
}
更多精彩
赞助商链接