在面试中遇到了这个问题 ,这个问题主要考面试者的多线程相关的知识,包括但不限于wait/notify 锁 Volatile变量3个方面。
3个线程 循环打印ABC 10次
第一种实现 Volatile 实现 依靠共同的state变量来保证 需要轮询
public class ThreadForDemo {
private static volatile int threestate=0;
static class MyThread extends Thread{
int state;
MyThread(int state){
this.state = state;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
while (true){
if(threestate%3==state){
break;
}
}
System.out.println((char)('A'+state));
threestate++;
}
}
}
public static void main(String[] args) {
MyThread one = new MyThread(0);
MyThread two = new MyThread(1);
MyThread three = new My