方法1:volatile + synchronized
public class ABCTest {
static volatile Integer count = 1;
public static void main(String[] args) {
new Thread(() -> {
try {
for (int i = 0; i < 10; ) {
while (count % 3 != 1) {
}
synchronized (count) {
if (count % 3 == 1) {
System.out.println("A");
count++;
i++;
}
}
}
} catch (Exception e) {
}
}, "A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; ) {
while (count % 3 != 2) {
}
synchronized (count) {
if (count % 3 == 2) {
System.out.println("B");
count++;
i++;
}
}
}
} catch (Exception e) {
}
}, "B").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; ) {
while (count % 3 != 0) {
}
synchronized (count) {
if (count % 3 == 0) {
System.out.println("C");
count++;
i++;
}
}
}
} catch (