同步器-Semaphore

信号量(Semaphore)概念上讲, 一个信号量管理许多的许可证 ( permit ) 。 为了通过信号量 , 线程通过调用acquire 请求许可 。 其实没有实际的许可对象 , 信号量仅维护一个计数 。 许可的数目是固定的, 由此限制了通过的线程数量 。 其他线程可以通过调用 release释放许可。 而且 , 许可不是二必须由获取它的线程释放。 事实上 , 任何线程都可以释放任意数目的许可 , 这可能会增加许可数目以至于超出初始数目。

Semaphore可以用于做流量控制,特别公用资源有限的应用场景,比如数据库连接。假如有一个需求,要读取几万个文件的数据,因为都是IO密集型任务,我们可以启动几十个线程并发的读取,但是如果读到内存后,还需要存储到数据库中,而数据库的连接数只有10个,这时我们必须控制只有十个线程同时获取数据库连接保存数据

public class SemaphoreTest {
private static final int THREAD_COUNT = 30;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
private static Semaphore s = new Semaphore(5);
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
final int j = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
//System.out.println(Thread.currentThread().getId() +" start work " + j);
s.acquire();
Thread.sleep(10000);
System.out.println(Thread.currentThread().getId() + " working " + j);
s.release();
System.out.println(Thread.currentThread().getId() +" end work " + j);
} catch (InterruptedException e) {
}
}
});
}
threadPool.shutdown();
}
}


猜你喜欢

转载自blog.csdn.net/qq_15140841/article/details/80373610
今日推荐