package dev.elaine.concurrency;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

public final class SynchronizerSample {
    private SynchronizerSample() {
    }

    public static void main(String[] args) throws InterruptedException {
        Semaphore permits = new Semaphore(2);
        CountDownLatch finished = new CountDownLatch(3);
        CyclicBarrier startTogether = new CyclicBarrier(3, () -> System.out.println("三项任务同时开始"));

        List<Thread> workers = java.util.stream.IntStream.rangeClosed(1, 3)
                .mapToObj(index -> Thread.ofPlatform().name("任务-" + index).start(() -> {
                    try {
                        startTogether.await();
                        permits.acquire();
                        try {
                            System.out.println(Thread.currentThread().getName() + " 获得许可");
                        } finally {
                            permits.release();
                        }
                    } catch (InterruptedException exception) {
                        Thread.currentThread().interrupt();
                    } catch (Exception exception) {
                        throw new IllegalStateException(exception);
                    } finally {
                        finished.countDown();
                    }
                }))
                .toList();

        finished.await();
        for (Thread worker : workers) {
            worker.join();
        }
        System.out.println("全部完成");
    }
}
