之前遇到过这个问题,直接上代码记录下:
public class RunableTest implements Runnable {
volatile int target="A".codePointAt(0);
static int minOrder="A".codePointAt(0);
static int maxOrder="C".codePointAt(0);
@Override
public void run() {
synchronized (this){
int order=Thread.currentThread().getName().codePointAt(0);
for (int i=0;i<10;i++){
while (target!=order){
try{
wait();
}catch (Exception ex){
}
}
System.out.println(Thread.currentThread().getName());
target=order+1;
if(target>maxOrder){
target=minOrder;
}
notifyAll();
}
}
}
}public class TestMain {
public static void main(String[] args){
Runnable runnable=new RunableTest();
Thread threadA=new Thread(runnable,"A");
Thread threadB=new Thread(runnable,"B");
Thread threadC=new Thread(runnable,"C");
threadA.start();
threadB.start();
threadC.start();
}
}
执行结果
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C