Semaphore 簡單應用

@Slf4j
public class SemaphoreTest {
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        // 5個信號量
        Semaphore semaphore = new Semaphore(5);
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            final int no = i;

            executorService.submit(() -> {
                try {
                    semaphore.acquire();
                    log.info("Accessing: " + no);
                    Thread.sleep(random.nextInt(500));
                    semaphore.release();
                    // 可用 permit
                    log.info("------ " + semaphore.availablePermits());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章