package com.yuhl.right.ali;
import java.util.concurrent.TimeUnit;
/**
* //1、编写代码,使用3个线程,1个线程打印X,一个线程打印Y,一个线程打印Z,同时执行连续打印10次"XYZ"
*/
public class PrintXYZ10Times2 {
//打印的次数
//private static volatile Integer COUNT = 0;
private static Integer COUNT = 0;
/**
* 打印标识
* 0:标识打印x
* 1:标识打印Y
* 2:标识打印Z
*/
//private static volatile Integer FLAG = 0;
private static Integer FLAG = 0;
public static void main(String[] args) {
//X的打印逻辑
new Thread(() -> {
while (true) {//一直会执行,变量的改变一定要在if内写
if (FLAG == 0) {
System.out.print("第"+(COUNT +1) +"次打印: X ");
FLAG = 1;
}
try {
TimeUnit.MICROSECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
//Y的打印逻辑
new Thread(() -> {
while (true) {
if (FLAG == 1) {
System.out.print("Y ");
FLAG = 2;
}
try {
TimeUnit.MICROSECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
//Z的打印逻辑
new Thread(() -> {
while (true) {
if (FLAG == 2) {
System.out.println("Z ");
COUNT++;
if(COUNT == 10){
System.exit(0);
}
FLAG = 0;
}
try {
TimeUnit.MICROSECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}