标签:clu rri not seconds void lis this factory override
package club.interview.algorithm.print; import io.netty.util.concurrent.DefaultThreadFactory; import java.util.concurrent.*; /** * 多线程打印 * -- 2个线程交替打印 AB 换行 * -- 3个线程交替打印 ABC 换行 * -- 2/3个线程交替打印 HHO 换行 * - 统一思路 * -- 统一任务类 ,寻找执行线程,设定打印内容 * <p> * code * -- 用线程池 (规范) * -- 定义外部成员变量用final (专业) * * -- 思路来自 多线程打印 从 0 - 100 * {@link Zero2Hundred} * @author QuCheng on 2020/9/9. */ public class ABC { /** * 自己定义打印内容,想打啥打啥 */ private final char[] threads = new char[]{‘A‘, ‘B‘, ‘C‘, ‘D‘}; /** * 打印次数 */ private final int times = 10; /** * 总计操作次数 */ private final int size = times * threads.length; /** * 开始 */ private int count = 0; private void waitNotifyCount() { ExecutorService es = new ThreadPoolExecutor(threads.length, threads.length, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new DefaultThreadFactory("Qc")); for (int i = 0; i < threads.length; i++) { es.execute(new Task(i)); } es.shutdown(); } 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 % threads.length == id) { // 设置执行的内容 if (id < (threads.length - 1)) { System.out.print(threads[id]); } else { System.out.println(threads[id]); } count++; Task.class.notifyAll(); } else { try { Task.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } public static void main(String[] args) { ABC abc = new ABC(); abc.waitNotifyCount(); } }
标签:clu rri not seconds void lis this factory override
原文地址:https://www.cnblogs.com/nightOfStreet/p/13640557.html