注意如果不满足条件要及时让出CPU,防止陷入死循环。
package com.qidong;
public class MJ3 {
volatile static int flag = 0;
public static void main(String[] args) {
new Thread(()->{
while (true){
if (flag % 3 == 0){
System.out.printf("a");
flag++;
}else{
try {
Thread.sleep(0);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}).start();
new Thread(()->{
while (true){
if (flag % 3 == 1){
System.out.printf("b");
flag++;
}else {
try {
Thread.sleep(0);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}).start();
new Thread(()->{
while (true){
if (flag % 3 == 2){
System.out.printf("c");
flag++;
}else{
try {
Thread.sleep(0);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}).start();
}
}