代碼如下: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()無法一直占用資源.
添加回答
舉報
0/150
提交
取消