Semaphore(信号量)
相当于阻塞队列一样,semaphore相当于一个令牌许可,如果你设置了20个许可,则一次最多只能同时并发20个线程。初始令牌为0,每次执行一个线程,则acquire一个令牌,如果令牌不够,则阻塞,当线程用完的时候,release掉一个令牌。下面是Demo:
public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); Semaphore sem = new Semaphore(20); for (i = 0; i < 200; i++) { Runnable runnable = new Thread() { @Override public void run() { try { sem.acquire(); // 获取令牌 System.out.printf("我拿到了令牌, 现在还剩下["+ sem.availablePermits() +"]\n"); Thread.sleep(2000); sem.release(); // 释放令牌 } catch (InterruptedException e) { e.printStackTrace(); } } }; executorService.execute(runnable); } }