Java优雅的停止线程

 

程序代码:

class TPTInterrupt {
    private Thread thread;
    public void start() {
        thread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (current.isInterrupted()) {
                    System.out.println("料理后事");
                    break;
                }
                try {
                    Thread.sleep(2000);
                    System.out.println("将结果保存");
                } catch (InterruptedException e) {
                    current.interrupt();
                }
            }
        }, "监控线程");
        thread.start();
    }
    public void stop() {
        thread.interrupt();
    }
}

 public static void main(String[] args) throws 
     InterruptedException {
        TPTInterrupt t = new TPTInterrupt();
        t.start();
        Thread.sleep(3500);
        System.out.println("stop");
        t.stop();
    }    

 

posted @ 2021-05-05 14:40  一名不断学习的程序猿  阅读(91)  评论(0)    收藏  举报