創(chuàng)建3個線程run一個method方法,第一個線程啟動間隔10ms啟動第二個線程再隔200ms啟動第三個線程。并沒有對線程2作出超過線程3的限制,但是每次都是線程3先執(zhí)行,這是什么意思?后面試了下2000ms執(zhí)行的順序才和代碼順序一樣。下面附上代碼,請各位看官指教!public?class?ChangeLock?{ private?String?lock?=?"lock"; private?void?method(){ synchronized?(lock)?{ try?{ System.out.println("當(dāng)前線程?:?"??+?Thread.currentThread().getName()?+?"開始"); if(Thread.currentThread().getName().equals("t1"))lock?=?"1"; Thread.sleep(2000); System.out.println("當(dāng)前線程?:?"??+?Thread.currentThread().getName()?+?"結(jié)束"+lock+"內(nèi)存地址:"+System.identityHashCode(lock)); }?catch?(InterruptedException?e)?{ e.printStackTrace(); } } } public?static?void?main(String[]?args)?throws?InterruptedException?{ final?ChangeLock?changeLock?=?new?ChangeLock(); Thread?t1?=?new?Thread(()->changeLock.method(),"t1"); Thread?t2?=?new?Thread(()->(new?ChangeLock()).method(),"t2"); t1.start(); Thread.sleep(10); t2.start(); Thread.sleep(200); Thread?t3=new?Thread((new?ChangeLock())::method,"t3"); t3.start(); } }執(zhí)行結(jié)果:當(dāng)前線程 : t1開始當(dāng)前線程 : t1結(jié)束1內(nèi)存地址:1901608479當(dāng)前線程 : t3開始當(dāng)前線程 : t3結(jié)束lock內(nèi)存地址:460860509當(dāng)前線程 : t2開始當(dāng)前線程 : t2結(jié)束lock內(nèi)存地址:460860509沒做更多的測試,想想200ms的時間夠cpu來說已經(jīng)很長了,為什么t3總能在t2線程之前執(zhí)行???
2 回答

添加回答
舉報
0/150
提交
取消