请问5.6节如何退出循环呀,没有补充呀

来源:5-7 恢复中断

甘林峰

2019-09-20

5.7节说会回来补充的

写回答

2回答

悟空

2019-09-20

5.6退出循环的代码在git更新了,就是在catch时,增加一个Thread.currentThread().interrupt();

代码如下:

public class RightWayStopThreadInProd implements Runnable {

    @Override
    public void run() {
        while (true && !Thread.currentThread().isInterrupted()) {
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                //保存日志、停止程序
                System.out.println("保存日志");
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
            Thread.sleep(2000);
    }

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


2
2
悟空
回复
imheyan
也可以
2022-04-13
共2条回复

甘林峰

提问者

2019-09-20

谢谢了

0
0

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程