题目:
编写代码,使用3个线程,1个线程打印X,一个线程打印Y,一个线程打印Z,同时执行连续打印10次"XYZ"
思路:
需要两个变量:
- 一个记录打印的次数COUNT:0,1,2,3,4,5,6,7,8,9
- 另一个记录该那个线程打印了FLAG: 0-打印X,1-打印Y,2-打印Z
1.代码如下:
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();
}
}
2.运行结果如下:
"C:\Program Files\Java\jdk1.8.0_201\bin\java.exe"
第1次打印: X Y Z
第2次打印: X Y Z
第3次打印: X Y Z
第4次打印: X Y Z
第5次打印: X Y Z
第6次打印: X Y Z
第7次打印: X Y Z
第8次打印: X Y Z
第9次打印: X Y Z
第10次打印: X Y Z
Process finished with exit code 0
3.以更容易理解的方式写代码
3.1 PrintXYZ.java
package com.yuhl.test001;
import java.util.concurrent.TimeUnit;
/**
* @author yuhl
* @Date 2020/10/29 21:46
* @Classname PrintXYZ
* @Description TODO
*/
public class PrintXYZ {
//打印的次数1--10
static volatile int count = 0;
/**
* 1:让X线程打印
* 2:让Y线程打印
* 3:让Z线程打印
*/
static volatile int flag = 1;
public static void main(String[] args) {
new Thread(new Runnable(){
@Override
public void run() {
while (true) {
if(flag == 1){
System.out.print("X ");//打印X
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = 2;
}
}
}
},"X").start();
new Thread(new Runnable(){
@Override
public void run() {
while (true) {
if(flag == 2){
System.out.print("Y ");//打印Y
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = 3;
}
}
}
},"Y").start();
new Thread(new Runnable(){
@Override
public void run() {
while (true) {
if(flag == 3){
System.out.print("Z ");//打印Z
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count++ == 9) {//如果为10 次则系统停止
System.exit(0);//系统停止
}
System.out.println();//换行
flag = 1;
}
}
}
},"Z").start();
}
}
3.2 运行结果
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
X Y Z
Process finished with exit code 0