亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

為什么函數在for循環內部,t1執行Thread.sleep()無法一直占用資源?

為什么函數在for循環內部,t1執行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("休眠結束");// mt.flag=1;} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}在線程t1,t2,t3啟動后,t1調用sleep(100000)后,t1不是應該占據資源不釋放鎖嗎?怎么線程t2,t3還可以繼續執行?反復測試發現:t1.sleep()在主線程中執行時暫停的是當前線程相當于Thread.sleep(),并非運行中的t1線程,另外將for(int i =0;i<50 && flag ==0;i++){ }放在同步函數內部,就會出現sleep時占用資源的情況,只有t1得到執行 , 函數放在for循環內部,就會t1 t2t3交替無序執行,為什么函數在for循環內部,t1執行Thread.sleep()無法一直占用資源.
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

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

查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 285 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號