import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreTest {
public static void main(String[] args) {
// 线程池
ExecutorService exec = Executors.newCachedThreadPool();
// 只能5个线程同时访问
final Semaphore semp = new Semaphore(5);
// 模拟20个客户端访问
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
// 获取许可
semp.acquire();
System.out.println("Accessing: " + NO);
TimeUnit.SECONDS.sleep(2L);
// 访问完后,释放
semp.release();
System.out.println("----------------- " + semp.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}
}
参考:http://www.cnblogs.com/whgw/archive/2011/09/29/2195555.html

本文通过一个Java示例展示了如何使用Semaphore来限制并发访问的数量。示例中创建了一个线程池,并利用Semaphore确保只有五个线程能同时访问资源,其余线程则需等待。每个线程访问资源两秒后释放Semaphore许可。
988

被折叠的 条评论
为什么被折叠?



