1. 程式人生 > 實用技巧 >多執行緒列印:兩個執行緒列印AB,三個執行緒列印ABC

多執行緒列印:兩個執行緒列印AB,三個執行緒列印ABC

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