信号量Semaphore用来控制同时访问特定资源的线程数量,通过协调各个线程,保证公平合理的使用公共资源。
- Semaphore的acquire()获取一个许可,release()归还一个许可。
- int availablePermits():返回信号量中可用线程数
- int getQueueLength():返回正在等待的线程数
- boolean hasQueuedThreads():返回是否有线程在等待
- void reducePermits(int reduction):减少reduction个许可证,是个protected方法
- 以下例子虽然有30个线程在执行,但是只允许10个并发执行:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author pengjunzhe
*/
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");
s.release();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
threadPool.shutdown();
}
}