利用volatile的立即可见性:
package com.zcj.thread;
public class PrintABC2 {
private volatile int status =1;
public void printA(){
while(status!=1){}
System.out.print("A");
status=2;
}
public void printB(){
while(status!=2){}
System.out.print("B");
status=3;
}
public void printC(){
while(status!=3){}
System.out.println("C");
status=1;
}
public static void main(String[] args){
PrintABC2 print = new PrintABC2();
Thread threadA = new Thread(new RunnableA2(print));
Thread threadB = new Thread(new RunnableB2(print));
Thread threadC = new Thread(new RunnableC2(print));
threadA.start();
threadB.start();
threadC.start();
}
}class RunnableA2 implements Runnable{
private PrintABC2 print;
public RunnableA2(PrintABC2 print) {
super();
this.print = print;
} @Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;
i<10;
i++){
print.printA();
}
}
}
class RunnableB2 implements Runnable{
private PrintABC2 print;
public RunnableB2(PrintABC2 print) {
super();
this.print = print;
} @Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;
i<10;
i++){
print.printB();
} }
}
class RunnableC2 implements Runnable{
private PrintABC2 print;
public RunnableC2(PrintABC2 print) {
super();
this.print = print;
} @Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;
i<10;
i++){
print.printC();
}
}
}
【java多线程---顺序打印ABC的三种实现---volatile方式】
推荐阅读
- 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组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)