import java.util.concurrent.TimeUnit;
public class Shutdown {
public static void main(String[] args) throws Exception{
Runner runner1 = new Runner();
Thread thread1 = new Thread(runner1, "runner1");
thread1.start();
TimeUnit.SECONDS.sleep(1);
thread1.interrupt();//main线程对thread1线程进行中断,达到取消或停止任务的目的
Runner runner2 = new Runner();
Thread thread2 = new Thread(runner2, "runner2");
thread2.start();
TimeUnit.SECONDS.sleep(1);
runner2.cannel();
}
private static class Runner implements Runnable {
private long i;
private volatile boolean on = true;//通过一个变量来控制是否需要停止任务并终止线程
@Override
public void run() {
while(on && !Thread.currentThread().isInterrupted()) {
i++;
}
System.out.println("count i = " + i);
}
public void cannel() {
on = false;
}
}
}
通过中断或者设置控制变量来终止线程,是一种比较安全地做法,它可以让线程有机会去处理它占用的资源。
另外,是由于main线程和runner线程同时对on访问和修改,volatile关键字修饰后,所有对on的访问和修改都会以共享内存为准~也就是说,一个线程对其修改了,所有线程会感知到变化,从而去共享内存中取得值。