Loading

Semaphore使用

1.概念

Semaphore是计数信号量。Semaphore管理一系列许可。每个acquire方法阻塞,直到有一个许可证可以获得然后拿走一个许可证;每个release方法增加一个许可,这可能会释放一个阻塞的acquire方法。然而,其实并没有实际的许可这个对象,Semaphore只是维持了一个可获得许可证的数量。

2.使用

public class TestSemaphore {
    public static void main(String[] args) {
        Semaphore s = new Semaphore(2);

        // 可以设置为公平锁
        //Semaphore s = new Semaphore(2, true);

        new Thread(() -> {
            try {
                s.acquire(); // 阻塞方法,拿许可,拿到继续往下执行,拿不到阻塞方法

                System.out.println("T1 running...");
                Thread.sleep(2000);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release(); // 释放许可
            }
        }).start();

        new Thread(() -> {
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(2000);
                System.out.println("T2 running...");

                s.release(); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
posted @ 2022-01-24 23:40  ZT丶  阅读(32)  评论(0编辑  收藏  举报