Semaphore(信号量),用于做限流处理,比如说同时只允许5五个人访问,超过五个人访问就需要等待,类似这样的需求,下面的案例可以看出执行是五个五个的执行,等上一个五个执行完了,才会执行下一个
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class UseSemaphore {public static void main(String[] args) {// 线程池ExecutorService exec = Executors.newCachedThreadPool();// 只能5个线程同时访问final Semaphore semp = new Semaphore(5);// 模拟20个客户端访问for (int index = 0; index < 20; index++) {final int NO = index;Runnable run = new Runnable() {public void run() {try {// 获取许可semp.acquire();System.out.println("Accessing: " + NO);//模拟实际业务逻辑Thread.sleep((long) (Math.random() * 10000));// 访问完后,释放semp.release();} catch (InterruptedException e) {}}};exec.execute(run);}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}//System.out.println(semp.getQueueLength());// 退出线程池exec.shutdown();}}
