Semaphore

2021-01-06  本文已影响0人  zzj0990

信号量,最多可以有多少线程去执行。
使用的场景:限流
例如:卖票窗口,收费高速口等

public class T11_TestSemaphore {
    public static void main(String[] args) {
        // Semaphore s = new Semaphore(2);
        Semaphore s = new Semaphore(2, true); // 默认第二个参数为true,内部用队列实现
        // 允许一个线程同时执行
        // Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire(); // 谁抢占到该信号量 谁就可以执行

                System.out.println("T1 running...");
                Thread.sleep(200);
                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(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
执行结果:
T1 running...
T1 running...
T2 running...
T2 running...

Process finished with exit code 0
上一篇 下一篇

猜你喜欢

热点阅读