packageclub.interview.algorithm.print;importio.netty.util.concurrent.DefaultThreadFactory;import java.util.concurrent.*;/*** 多线程打印
* -- 2个线程交替打印 AB 换行
* -- 3个线程交替打印 ABC 换行
* -- 2/3个线程交替打印 HHO 换行
* - 统一思路
* -- 统一任务类 ,寻找执行线程,设定打印内容
*
* code
* -- 用线程池 (规范)
* -- 定义外部成员变量用final (专业)
*
* -- 思路来自 多线程打印 从 0 - 100
* {@linkZero2Hundred}
*@authorQuCheng on 2020/9/9.*/
public classABC {/*** 自己定义打印内容,想打啥打啥*/
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 voidwaitNotifyCount() {
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(newTask(i));
}
es.shutdown();
}class Task implementsRunnable {private final intid;public Task(intid) {this.id =id;
}
@Overridepublic voidrun() {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 voidmain(String[] args) {
ABC abc= newABC();
abc.waitNotifyCount();
}
}