带有信号量及计数器的多线程线程池
package org.lance.concurrent;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class SemaphoreCountDownExecutor {private Semaphore semaphore;private CountDownLatch countDownLatch;private ExecutorService executor;public SemaphoreCountDownExecutor(final int semaphorePermits,final int count) {semaphore = new Semaphore(semaphorePermits);executor = Executors.newFixedThreadPool(semaphorePermits);countDownLatch = new CountDownLatch(count);}public void await(){try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}executor.shutdown();}public void submit(final Runnable command) throws InterruptedException{countDownLatch.countDown();semaphore.acquire();try {executor.execute(new Runnable() {@Overridepublic void run() {try {command.run();} catch (Exception e) {e.printStackTrace();} finally {semaphore.release();}}});} catch (Exception e) {semaphore.release();e.printStackTrace();}}public static void main(String[] args) {int count = 100;SemaphoreCountDownExecutor executor = new SemaphoreCountDownExecutor(8, count);try {for (int i = 0; i < count; i++) {final int core = i;executor.submit(new Runnable() {@Overridepublic void run() {System.out.println(core+"----------"+Thread.currentThread().getName());try {Thread.sleep(new Random().nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}}});}executor.await();} catch (InterruptedException e) {e.printStackTrace();}}}