importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;publicclassNumberPrintimplementsRunnable{privateintstate=0;privateLocklock=newReentrantLock();privatefinalintN=4;privateString[]chars={"A","B","C","D"};privateNumberPrint(){}@Overridepublicvoidrun(){for(inti=0;icreateThread(i); }}privatevoidcreateThread(inti){newThread(newRunnable(){@Overridepublicvoidrun(){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,为什么有时结果会不对呢?
相关分类