多線程打印:三個線程輪流打印0到100


package club.interview.algorithm.print;

import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.*;

/**
 * 3個線程從0到100輪流打印。要求輸出結果如下
 * Thread-0:0
 * Thread-1:1
 * Thread-2:2
 * Thread-0:3
 * <p>
 * 知識點:
 * 1. 類鎖的wait、notify
 * 2. 使用線程池哦! - 不需要隊列存儲任務
 * 3. 可定制線程數 - 修改threadNums  {@link Zero2Hundred#threadNums}
 * <p>
 *
 * @author QuCheng on 2020/4/10.
 */
public class Zero2Hundred {

    int threadNums = 3, keepAliveTime = 0;

    int count = 0, size = 100;

    class Task implements Runnable {
        private final int id;

        public Task(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (Task.class) {
                    if (count > size) {
                        break;
                    }
                    if (count % threadNums == id) {
                        System.out.println("Thread-" + id + ":" + count++);
                        Task.class.notifyAll();
                    } else {
                        try {
                            Task.class.wait();
                        } catch (InterruptedException e) {
                            System.out.println("來呀 - 打斷我呀!");
                        }
                    }
                }
            }
        }
    }

    private void waitNotify() {
        ExecutorService executorService = new ThreadPoolExecutor(threadNums, threadNums, keepAliveTime,
                TimeUnit.MICROSECONDS, new SynchronousQueue<>(), new DefaultThreadFactory("Qc-"));
        for (int i = 0; i < threadNums; i++) {
            executorService.execute(new Task(i));
        }
        executorService.shutdown();
    }

    public static void main(String[] args) {
        Zero2Hundred z = new Zero2Hundred();
        z.waitNotify();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM