Loading

停止线程

正确的停止线程

使用interrupu来通知,而不是强制
interrupu仅仅是通知,线程本身具有决定权是否终止,原因:线程本身了解自己的运行状态,即:自己的任务是不是已经完成了,所以把决定权交给线程自己

public class RightWayStop implements Runnable {

    @Override
    public void run() {
        int num = 0;
        while(!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2){
	//判断Thread是否被interrupt,还没被中断,才执行下面的内容。
            if(num % 10000 == 0){
                System.out.println(num + "是10000的倍数");
            }
            num++;
        }
        System.out.println("任务运行结束了");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStop());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

停止时遇到阻塞

posted @ 2021-12-22 23:54  Zhbeii  阅读(39)  评论(0)    收藏  举报