package dev.elaine.concurrency;

import java.util.concurrent.CountDownLatch;

public final class InterruptionSample {
    private InterruptionSample() {
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch started = new CountDownLatch(1);
        Thread worker = Thread.ofPlatform().name("可取消工作线程").start(() -> runWorker(started));

        started.await();
        worker.interrupt();
        worker.join();
        System.out.println("工作线程已结束=" + !worker.isAlive());
    }

    private static void runWorker(CountDownLatch started) {
        try {
            started.countDown();
            while (!Thread.currentThread().isInterrupted()) {
                Thread.sleep(1_000);
            }
        } catch (InterruptedException exception) {
            Thread.currentThread().interrupt();
            System.out.println("收到中断，开始清理");
        }
    }
}
