Semaphore(信号量),用于做限流处理,比如说同时只允许5五个人访问,超过五个人访问就需要等待,类似这样的需求,下面的案例可以看出执行是五个五个的执行,等上一个五个执行完了,才会执行下一个

    1. import java.util.concurrent.ExecutorService;
    2. import java.util.concurrent.Executors;
    3. import java.util.concurrent.Semaphore;
    4. public class UseSemaphore {
    5. public static void main(String[] args) {
    6. // 线程池
    7. ExecutorService exec = Executors.newCachedThreadPool();
    8. // 只能5个线程同时访问
    9. final Semaphore semp = new Semaphore(5);
    10. // 模拟20个客户端访问
    11. for (int index = 0; index < 20; index++) {
    12. final int NO = index;
    13. Runnable run = new Runnable() {
    14. public void run() {
    15. try {
    16. // 获取许可
    17. semp.acquire();
    18. System.out.println("Accessing: " + NO);
    19. //模拟实际业务逻辑
    20. Thread.sleep((long) (Math.random() * 10000));
    21. // 访问完后,释放
    22. semp.release();
    23. } catch (InterruptedException e) {
    24. }
    25. }
    26. };
    27. exec.execute(run);
    28. }
    29. try {
    30. Thread.sleep(10);
    31. } catch (InterruptedException e) {
    32. e.printStackTrace();
    33. }
    34. //System.out.println(semp.getQueueLength());
    35. // 退出线程池
    36. exec.shutdown();
    37. }
    38. }

    https://blog.csdn.net/u010316188/article/details/86562395