• 24.Semaphore


    Semaphore
        在进程方面完成信号线的控制,可以控制某个资源下,可被同时访问的线程个数。对系统的访问量进行评估,信号量维护了一个许可集;在许可前会阻塞每一个 semaphore.acquire() ,然后再获取该许可,每一个release() 添加一个许可,从而
        可能释放一个正在阻塞的获取者,但是,不使用实际的许可对象,Semaphore只对可用许可的号码进去计算,并采取行动,拿到信号量的线程则进入代码,否则就等待。
    semaphore.acquire();//1.获取许可
    semaphore.release();//3.访问完毕,释放
    1. package demo1;
    2. import java.util.concurrent.ExecutorService;
    3. import java.util.concurrent.Executors;
    4. import java.util.concurrent.Semaphore;

    5. public class DemoSemaphore {

    6. public static void main(String[] args) {
    7. ExecutorService executorService = Executors.newCachedThreadPool();
    8. Semaphore semaphore = new Semaphore(3);
    9. for (int i=0;i<=20;i++){
    10. final int no =i;
    11. Runnable runnable = new Runnable() {
    12. @Override
    13. public void run() {
    14. try {
    15. semaphore.acquire();//1.获取许可
    16. System.err.println("systme:"+no);
    17. Thread.sleep((long) (Math.random()*1000));//2.模拟业务耗时
    18. semaphore.release();//3.访问完毕,释放 ,如果屏蔽下面的语句,则在控制台只能打印5条记录,之后线程一直阻塞
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. }finally {
    22. System.err.println("。。。");
    23. }
    24. }
    25. };
    26. executorService.execute(runnable);
    27. }
    28. executorService.shutdown();
    29. }
    30. }
    31. 输出:
    32. systme:0 systme:1 systme:2 。。。 systme:3 。。。 systme:4 。。。 systme:5 。。。 systme:6 。。。 systme:7 。。。 systme:8 。。。 systme:9 。。。 systme:10 。。。 systme:11 。。。 systme:12 。。。 systme:13 。。。 systme:14 。。。 systme:15 。。。 systme:16 。。。 systme:17 。。。 systme:18 。。。 systme:19 。。。 systme:20 。。。 。。。 。。。
  • 相关阅读:
    正则表达式 (记录中...)
    css 坑记
    WebApi 中使用 Token
    WebApi 中使用 Session
    微信小程序 入门
    .net EF监控 MiniProfiler
    css布局
    移动端1像素边框问题
    移动端页面自适应解决方案:rem 布局篇
    js重点知识总结
  • 原文地址:https://www.cnblogs.com/xxt19970908/p/7337131.html
Copyright © 2020-2023  润新知