第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么函數(shù)在for循環(huán)內(nèi)部,t1執(zhí)行Thread.sleep()無法一直占用資源?

為什么函數(shù)在for循環(huán)內(nèi)部,t1執(zhí)行Thread.sleep()無法一直占用資源?

精慕HU 2022-05-17 19:15:29
代碼如下:class MyThread implements Runnable{volatile int flag = 0;private int ticket=40;public void run(){for(int i =0;i<50 && flag ==0;i++){sale();}}public synchronized void sale(){if(this.ticket>0){System.out.println(Thread.currentThread().getName()+"賣票---->"+(this.ticket--));try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();e.printStackTrace();}}}}public class ThreadTest{public static void main(String args[]){MyThread mt= new MyThread();Thread t1 = new Thread(mt,"一號窗口");Thread t2 = new Thread(mt,"二號窗口");Thread t3 = new Thread(mt,"三號窗口");try {t1.start();t2.start();t3.start();System.out.println("休眠開始");t1.sleep(100000);System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");System.out.println("休眠結(jié)束");// mt.flag=1;} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}在線程t1,t2,t3啟動后,t1調(diào)用sleep(100000)后,t1不是應(yīng)該占據(jù)資源不釋放鎖嗎?怎么線程t2,t3還可以繼續(xù)執(zhí)行?反復(fù)測試發(fā)現(xiàn):t1.sleep()在主線程中執(zhí)行時暫停的是當(dāng)前線程相當(dāng)于Thread.sleep(),并非運行中的t1線程,另外將for(int i =0;i<50 && flag ==0;i++){ }放在同步函數(shù)內(nèi)部,就會出現(xiàn)sleep時占用資源的情況,只有t1得到執(zhí)行 , 函數(shù)放在for循環(huán)內(nèi)部,就會t1 t2t3交替無序執(zhí)行,為什么函數(shù)在for循環(huán)內(nèi)部,t1執(zhí)行Thread.sleep()無法一直占用資源.
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經(jīng)驗 獲得超7個贊

sleep(100000)你這個是在票賣完之后才執(zhí)行的,所以你看不到停頓

查看完整回答
反對 回復(fù) 2022-05-23
  • 1 回答
  • 0 關(guān)注
  • 292 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號