直接上代码
public class ShutDown {
public static void main(String[] args) throws InterruptedException {
Runner one = new Runner();
Thread countThread = new Thread(one, "countThread");
countThread.start();
TimeUnit.SECONDS.sleep(1);
countThread.interrupt();
Runner two = new Runner();
countThread = new Thread(two, "countThread");
countThread.start();
TimeUnit.SECONDS.sleep(1);
two.cancel();
}
static class Runner implements Runnable {
private long value;
private volatile boolean on = true;
@Override
public void run() {
while (on && !Thread.currentThread().isInterrupted()) {
value++;
}
System.out.println("value: " + value);
}
public void cancel() {
this.on = false;
}
}
}