public class SemaphoreTest { //信号量,只允许 3个线程同时访问 private static Semaphore semaphore = new Semaphore(3); public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int num = i; executorService.submit(new Runnable() { @Override public void run() { showLog(num); } }); } executorService.shutdown(); } private static void showLog(int num) { //获取许可 try { semaphore.acquire(); //执行 System.out.println("Accessing: " + num); Thread.sleep(2000); //休眠2秒 } catch (InterruptedException e) { e.printStackTrace(); }finally { //释放 semaphore.release(); System.out.println("Release..." + num); } } }