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();
                }
            }
        }
    }

你可能感兴趣的:(Java多线程---顺利周期打印1-75的数字)