并发工具类之 Semaphore

x33g5p2x  于2021-12-18 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(226)

Semaphore (信号量) 是用来控制同时访问特定资源的线程数量,它可以协调各个线程,以保证公共资源被合理使用。

Semaphore 可以用于流量控制,特别是公共资源有限的场景,比如数据库连接。假如同时有 10 个线程需要连接数据库,但数据库的连接数只有 2 个,我们必须控制只有 2 个线程能同时获取数据库连接,否则会报错无法获取数据库连接,这时就可以使用 Semaphore 来做流量控制,代码如下:

public class TestSemaphore {
    private static final int THREAD_COUNT = 10;

    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    private static Semaphore s = new Semaphore(2);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(() -> {
                try {
                    // 获取许可,未获取许可前线程就停在这里等着
                    s.acquire();
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " save data");
                    // 释放许可
                    s.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
    }
}

控制台输出如下:

pool-1-thread-2 save data
pool-1-thread-1 save data
pool-1-thread-3 save data
pool-1-thread-4 save data
pool-1-thread-5 save data
pool-1-thread-6 save data
pool-1-thread-7 save data
pool-1-thread-8 save data
pool-1-thread-10 save data
pool-1-thread-9 save data

相关文章