多线程设计模式--two-phase termination

two-phase termination 等待线程执行终止处理再结束线程

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);
}
}


测试类
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");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值