• java线程池,信号量使用demo


    直接上代码

    package org.jimmy.threadtest20181121;
    
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.TimeUnit;
    
    public class TestThread20181128 {
    
        public Semaphore semaphore = new Semaphore(2, true);
        
        public static void main(String[] args) {
            try {
                TestThread20181128 testThread20181128 = new TestThread20181128();
                LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
                ThreadPoolExecutor201811281311 executor = new ThreadPoolExecutor201811281311(2, 10000, 3600, TimeUnit.SECONDS, workQueue);
                for(int i = 0 ; i < 10; i++) {
                    String id = i + "";
                    Thread thread = new Thread(testThread20181128.new LineUpThread(id));
                    executor.submit(thread);
                }
                executor.shutdown();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
        class LineUpThread implements Runnable {
    
            private String id;
            
            public LineUpThread(String id) {
                this.id = id;
            }
            
            @Override
            public void run() {
                try {
                    if(semaphore.availablePermits() > 0){
                        System.out.println("开始排队");
                    }
                    semaphore.acquire();
                    System.out.println("轮到编号" + id + "的客户了,可以开始购票了!");
                    System.out.println("编号" + id + "的客户已购票成功!");
                    semaphore.release();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
            
        }
        
    }

    运行结果:

    2015年10月-2016年3月 总计:5个月.
    2016年11月-2017年6月 总计:7个月.
    2017年7月-2018年4月 总计:9个月.
    2018年5月-2018年5月 总计:1个月.
    2018年6月-2018年12月 总计:6个月.
    2019年1月-2019年12月 总计11个月.
    2020年2月-2021年2月 总计13个月.
    所有总计:5+7+9+1+6+11+13=52个月(4年4个月).
    本人认同二元论.我是理想主义者,现实主义者,乐观主义者,有一定的完美主义倾向.不过,一直都是咸鱼(菜鸟),就算有机会,我也不想咸鱼翻身.(并不矛盾,因为具体情况具体分析)
    英语,高等数学,考研,其他知识学习打卡交流QQ群:946556683
  • 相关阅读:
    URL中的特殊字符 + % # & = ? /
    mvc 前端显示文本中的html标签处理
    URL中#号(井号)的作用
    自定义配置节 Section
    vshost.exe.config与.exe.config ;Debug目录与Release目录;bin目录与obj目录
    在MVC过滤器中获取触发的Controller、Action、参数 等
    js设置全局变量 ajax中赋值
    批处理 安装、卸载 window service
    [摘]HttpContext, HttpRequest, HttpResponse, HttpRuntime, HttpServerUtility
    摘要:ASP.NET的路由
  • 原文地址:https://www.cnblogs.com/JimmySeraph/p/10031776.html
Copyright © 2020-2023  润新知