三个线程,ABC 10次(volatile+synchronized(2 synchronized可以保证内存可见性,所以去掉status 的volatile修饰符)

时间:2023-12-25 17:44:37
package ThreadABC;

public class MyThread extends Thread {
public static int status = 0;
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if ("A".equals(Thread.currentThread().getName()) && status < 30 && status % 3 == 0) {
System.out.print("A");
status++;
} else if ("B".equals(Thread.currentThread().getName()) && status < 30 && status % 3 == 1) {
System.out.print("B");
status++; } else if ("C".equals(Thread.currentThread().getName()) && status < 30 && status % 3 == 2) {
System.out.println("C");
status++;
}
if (status == 30) {
break;
}
}
}
} public MyThread(String name) {
super(name);
}
}