Java學(xué)習(xí)中,目前在看多線(xiàn)程所調(diào)試的例題是經(jīng)典的多點(diǎn)售票程序?yàn)榱朔乐故燮秉c(diǎn)因?yàn)橘Y源不同步的原因,而賣(mài)出超過(guò)實(shí)際票數(shù)的票則使用了synchronized關(guān)鍵字結(jié)果的確不會(huì)再賣(mài)出-1票了但是調(diào)試結(jié)果貌似不太理想,如果票數(shù)少,就基本上是第一個(gè)售票點(diǎn)賣(mài)完了即便票數(shù)多(100張),線(xiàn)程也不是交替運(yùn)行,而是一時(shí)全A,一時(shí)全B請(qǐng)幫忙查看代碼是否有錯(cuò),邏輯是否合理謝謝!代碼:classTest24_04implementsRunnable{privateintpiao=10;publicvoidrun(){while(this.piao>0){this.fun();}}publicsynchronizedvoidfun(){if(this.piao>0){try{Thread.sleep(100);}catch(Exceptione){;}System.out.println(Thread.currentThread().getName()+"賣(mài)票了,剩余票數(shù):"+(this.piao--));}}}publicclassJavaTest24_04{publicstaticvoidmain(Stringargs[]){Test24_04t=newTest24_04();Threadt1=newThread(t,"售票點(diǎn)A");Threadt2=newThread(t,"售票點(diǎn)B");Threadt3=newThread(t,"售票點(diǎn)C");t1.start();t2.start();t3.start();}}//使用synchroized關(guān)鍵字實(shí)現(xiàn)線(xiàn)程對(duì)資源的同步操作
Java多線(xiàn)程處理同一個(gè)資源時(shí),線(xiàn)程幾乎不交替運(yùn)行
瀟湘沐
2019-04-13 08:36:48