/**

 * 控制并发,属于一种较常见的限流手段,通过信号量机制(如Java中的Semaphore)来控制

 * 假如有一个需求,要读取几万个文件的数据,因为都是IO密集型任务,我们可以启动几十个线程

 * 并发的读取,但是如果读到内存后,还需要存储到数据库中,而数据库的连接数只有10个,这时

 * 我们必须控制只有十个线程同时获取数据库连接保存数据,否则会报错无法获取数据库连接,

 * 使用Semaphore来控制并发数

 * @author Administrator

 *

 */

public class SemaphoreTest {


//并发线程的数量

private static final int THREADCOUNT = 30;

//控制并发,最多允许10个线程获得许可证

private static Semaphore semaphore = new Semaphore(10);

//创建线程池

private static ExecutorService executorService = Executors.newFixedThreadPool(THREADCOUNT);

public static void main(String[] args) {

for(int i=0;i<THREADCOUNT;i++){

executorService.execute(new Runnable() {

public void run() {

try {

semaphore.acquire();

System.out.println("执行相应的服务");

semaphore.release();

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

executorService.shutdown();

}

}