优雅停止线程

{
        Thread thread = new Thread(() -> {
            for (int j = 0; j < 300000; j++) {
                if (Thread.currentThread().isInterrupted()){
                    break;
                }
                System.out.println(j);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        Thread.sleep(300);
        System.out.println("end");
        thread.interrupt();
    }

  

posted @ 2024-05-09 17:23  每月工资一万八  阅读(7)  评论(0)    收藏  举报