正确地停止线程

2018-03-01 11:13:54来源:oschina作者:小小明童鞋人点击

分享
import java.util.concurrent.TimeUnit;
public class Shutdown {
public static void main(String[] args) throws InterruptedException {
Runner one = new Runner();
Thread countThread = new Thread(one,"CountThread");
countThread.start();
//睡眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束
TimeUnit.SECONDS.sleep(1);
countThread.interrupt();
Runner two = new Runner();
countThread = new Thread(two,"CountThread");
countThread.start();
//睡眠1秒,main线程对Runner two 进行取消,使CountThread能够感知on为false而结束
TimeUnit.SECONDS.sleep(1);
two.cancel();
}
private static class Runner implements Runnable {
private long i;
private volatile boolean on = true;
@Override
public void run() {
//如果当前线程没有被中断,变量i 自增
while (on && !Thread.currentThread().isInterrupted()) {
i++;
}
System.out.println("Count i = " + i);
}
public void cancel() {
on = false;
}
}

}

/** * 上述程序在执行过程中,main线程通过中断操作和cancel()方法均可使CountThread得意终止。 * 这种通过标识位或者中断操作的方式能够使线程在终止时有机会取清理资源,而不是武断地将线程停止, * 因此这种终止线程的做法更加安全和优雅。 */

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台