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