Java多线程---顺利周期打印1-75的数字

此题类似于打印循环打印ABC的问题
下面是实现方式

    private static final Integer FINAL_NUM = 75;
    private static Integer Start_NUM = 1;

    public static void main(String[] args) throws InterruptedException {
        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);

        ExecutorService poolService = Executors.newFixedThreadPool(3);
        poolService.execute(new Worker(a, b));
        poolService.execute(new Worker(b, c));
        poolService.execute(new Worker(c, a));
        Thread.sleep(1000);
        poolService.shutdownNow();
    }

    public static class Worker implements Runnable {
        private Semaphore current;
        private Semaphore next;

        public Worker(Semaphore current, Semaphore next) {
            this.current = current;
            this.next = next;
        }

        public void run() {
            while(true) {
                try {
                    // 获取当前的锁
                    if(Start_NUM > FINAL_NUM) {
                        break;
                    }
                    current.acquire(); // current - 1
                    for (int i = 0; i < 5; i++) {
                        System.out.println(Thread.currentThread().getName() + "," + Start_NUM++);
                    }

                    if(Start_NUM <= FINAL_NUM) {
                        next.release(); // next + 1
                    }
                } catch (InterruptedException e) {
                    e.fillInStackTrace();
                }
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 《裕语言》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 27,908评论 5 19
  • 1 Mini-batch梯度下降 Mini-batch解决了批量梯度下降单次迭代样本多,速度慢的问题,也解决了随机...
    冯凯onmyway阅读 1,975评论 2 3
  • 晚上吃完晚饭妈妈让我写作业,我边写边玩,把妈妈惹烦了,她狠狠的打了我两巴掌。我都觉得是后妈妈了,可是后来...
    郝丽君_67b1阅读 196评论 0 0
  • 看着渐渐悄然而去的故乡,我知道又要开启远离家乡的征程了。北京我来了!这是一个让人神秘向往的地方,无数的外地人都愿意...
    书色人生阅读 148评论 0 0
  • 2018年5月19日 周六 晴 早晨睡了个小懒觉,6:50起床。今天要上班,徐琦要去学儿童画...
    徐安然儿阅读 125评论 0 0