【Java|java 实现3个线程 依次打印ABC,并且循环10次】网上看到一个题目,要求3个线程依次打印ABC,并且循环10次,网上的版本比较多,这个是我实现的一个版本,共用一个Runnable对象,有点小缺陷,无法关联线程的名
字。
package com.mythread.test;
import java.util.concurrent.atomic.AtomicInteger;
public class TestAsynTreadXunlei {
public static void main(String argv[]) {AtomicInteger synObj = new AtomicInteger(0);
Runnable r = new PrintThread(synObj);
try {
Thread a = new Thread(r, "A");
Thread b = new Thread(r, "B");
Thread c = new Thread(r, "C");
a.start();
b.start();
c.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}class PrintThread implements Runnable { private AtomicInteger synObj;
public PrintThread(AtomicInteger synObj) {
this.synObj = synObj;
}
@Override
public void run() {
print();
}
public void print() {
for (int i = 0;
i < 10;
i++) {
try {synchronized (synObj) {
if (synObj.get() % 3 == 0) {
System.out.println("A");
synObj.set(synObj.get() + 1);
} else if (synObj.get() % 3 == 1 ) {
System.out.println("B");
synObj.set(synObj.get() + 1);
} else if (synObj.get() % 3 == 2 ) {
System.out.println("C");
synObj.set(synObj.get() + 1);
}
}} catch (Exception e) {
e.printStackTrace();
}
}
}
}
网上比较经典的一个版本(基于thread)
package com.mythread.test;
import java.util.concurrent.atomic.AtomicInteger;
public class TestAsynTreadXunlei {
public static void main(String argv[]) {AtomicInteger synObj = new AtomicInteger(0);
TestPrint a = new TestPrint(synObj, "A", 0);
TestPrint b = new TestPrint(synObj, "B", 1);
TestPrint c = new TestPrint(synObj, "C", 2);
a.start();
b.start();
c.start();
}
}class TestPrint extends Thread {
private AtomicInteger synObj;
private String name;
private int flag;
private int count = 0;
public TestPrint(AtomicInteger synObj, String name, int flag) {
this.synObj = synObj;
this.name = name;
this.flag = flag;
}
@Override
public void run() {
while (true) {
synchronized (synObj) {
if (synObj.get() % 3 == flag) {
synObj.set(synObj.get() + 1);
System.out.println(name);
count++;
synObj.notifyAll();
if (count == 10) {
break;
}
} else {
try {
synObj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)