控制并发线程数的Semaphore
Semaphore(信号量)使用来控制同时访问特定资源的线程数量.它通过协调各个线程,以保证合理的使用公共资源.
可以把它比作是控制流量的红绿灯.
public class SemaphoreTest {
private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); private Semaphore s = new Semaphore(10); public static void main(String [] args) { for(int i = 0; i< THREAD_COUNT; i++) { threadPool.execute( new Runnable() { public void run() { try { s.acquire(); System.out.println("save data"); s.release(); } } } ); } threadPool.shutDown(); }
}