package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * 并发控制 **/ public class SemaphoreTest { public static void main(String[] args) { test1(); } private static void test1() { ExecutorService executorService = Executors.newFixedThreadPool(20); Semaphore semaphore = new Semaphore(3);//资源最多可被3个线程并发访问 for (int i = 0; i < 20; i++) { executorService.execute(() -> { try { boolean b = semaphore.tryAcquire(1, 300, TimeUnit.MILLISECONDS);//获取许可,300超时,返回false System.out.println("SemaphoreTest.run " + Thread.currentThread().getName() + " b = " + b); Thread.sleep(280); semaphore.release(1);//释放许可 } catch (Exception e) { e.printStackTrace(); } }); } executorService.shutdown();//如果不shutdown工程不会结束 } }
可以控制并发的数量