多线程打印:三个线程轮流打印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();
    }
}

 

posted @ 2020-06-03 19:37  渠成  阅读(1538)  评论(0编辑  收藏  举报