概念:java
Semaphore(信号量)是用来控制同事访问特定资源的线程数量,它经过协调各个线程,已保证合理的使用公共资源。数据库
应用场景:并发
Semaphore 能够用于作流量控制,特别是共用资源有限的应用场景,好比数据库链接。假若有一个需求,要读取几万个文件的数据,由于都是IO密集型任务,咱们能够启动几十个线程并发的读取,可是若是读到内存后,还须要存储到数据库中。而数据库的链接数只有10个,这时咱们必须控制只有10个线程同时获取数据库链接保存数据,不然报错没法获取数据库链接。这个时候,就能够使用Semaphore来作流量控制。ide
package com.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class SemaphoreTest { private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); private static Semaphore s = new Semaphore(10); public static void main(String[] args) { for (int i = 0; i < THREAD_COUNT; i ++) { threadPool.execute(new Runnable() { @Override public void run() { try { s.acquire(); System.out.println("save DATA:" + System.currentTimeMillis()); s.release(); } catch (Exception e) { e.printStackTrace(); } } }); } threadPool.shutdown(); } }