java 三线程打印abc,多线程打印:两个线程打印AB,三个线程打印ABC

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值