Java并发编程-Semaphore使用
使用场景:Semaphore(信号量)同时运行多少个并发执行,比如我现在设置30个线程访问,可以通过Semaphore控制同时多个线程同时访问的,
代码如下:
public class SemaphoreTest {
private static final int THREAD_COUNT = 30;
private static final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);//设置30个线程
private static Semaphore semaphore = new Semaphore(10);//并发控制10个
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+"---------");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
});
}
threadPool.shutdown();
}
}
pool-1-thread-1---------
pool-1-thread-2---------
pool-1-thread-3---------
pool-1-thread-4---------
pool-1-thread-5---------
pool-1-thread-6---------
pool-1-thread-7---------
pool-1-thread-9---------
pool-1-thread-8---------
pool-1-thread-10---------
pool-1-thread-13---------
pool-1-thread-12---------
pool-1-thread-11---------
pool-1-thread-14---------
pool-1-thread-17---------
pool-1-thread-16---------
pool-1-thread-15---------
pool-1-thread-20---------
pool-1-thread-19---------
pool-1-thread-18---------
pool-1-thread-21---------
pool-1-thread-22---------
pool-1-thread-23---------
pool-1-thread-24---------
pool-1-thread-25---------
pool-1-thread-26---------
pool-1-thread-27---------
pool-1-thread-29---------
pool-1-thread-28---------
pool-1-thread-30---------
运行结果分析:可以看到输出时,一次输出10个,一共输出3次。也就是每次只允许10个线程进入执行任务。