猿问

多线程顺序打印ABCD

importjava.util.concurrent.locks.Lock;
importjava.util.concurrent.locks.ReentrantLock;
publicclassNumberPrintimplementsRunnable{
privateintstate=0;
privateLocklock=newReentrantLock();
privatefinalintN=4;
privateString[]chars={"A","B","C","D"};
privateNumberPrint(){
}
@Override
publicvoidrun(){
for(inti=0;icreateThread(i);
}
}
privatevoidcreateThread(inti){
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
while(state!=i){
};
lock.lock();
for(intj=0;jSystem.out.println(chars[i]);
}
state=(i+1)%4;
System.out.println(state);
}finally{
lock.unlock();
}
}
},"thread"+i).start();
}
publicstaticvoidmain(String[]args){
newNumberPrint().run();
}
}
顺序打印ABCD,为什么有时结果会不对呢?
一只甜甜圈
浏览 489回答 2
2回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答