优雅的终止线程

来源:互联网 发布:仓储流程优化的方法 编辑:程序博客网 时间:2024/05/22 22:01
public class ShutDownThread {


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.cancle();
}


//内部类
public static class Runner implements Runnable {
//变量i
private long i;

//标识符
boolean on = true;

public void run() {
// TODO Auto-generated method stub
//on为true 且 当前线程不调用被中断标志 变量i一直加下去
while (on&&!Thread.currentThread().isInterrupted()) {
i++;
}
System.out.println("count i =" + i );
}

public void cancle() {

on = false;
}

}
原创粉丝点击