国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

sleep和wait的區別

2019-11-08 18:46:56
字體:
來源:轉載
供稿:網友

Thread.sleep() VS Object.wait()

對于sleep()方法,我們首先要知道該方法是屬于Thread類中的。而wait()方法,則是屬于Object類中的。sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。在調用sleep()方法的過程中,線程不會釋放對象鎖。而當調用wait()方法的時候,線程會放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象調用notify()方法后本線程才進入對象鎖定池準備,獲取對象鎖進入運行狀態。

什么意思呢?舉個列子說明:

/** * java中的sleep()和wait()的區別 * @author Hongten * @date 2013-12-10 */public class TestD { public static void main(String[] args) { new Thread(new Thread1()).start(); try { Thread.sleep(5000); } catch (Exception e) { e.PRintStackTrace(); } new Thread(new Thread2()).start(); } private static class Thread1 implements Runnable{ @Override public void run(){ synchronized (TestD.class) { System.out.println("enter thread1..."); System.out.println("thread1 is waiting..."); try { //調用wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池 TestD.class.wait(); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 is going on ...."); System.out.println("thread1 is over!!!"); } } } private static class Thread2 implements Runnable{ @Override public void run(){ synchronized (TestD.class) { System.out.println("enter thread2...."); System.out.println("thread2 is sleep...."); //只有針對此對象調用notify()方法后本線程才進入對象鎖定池準備獲取對象鎖進入運行狀態。 TestD.class.notify(); //================== //區別 //如果我們把代碼:TestD.class.notify();給注釋掉,即TestD.class調用了wait()方法,但是沒有調用notify() //方法,則線程永遠處于掛起狀態。 try { //sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程, //但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。 //在調用sleep()方法的過程中,線程不會釋放對象鎖。 Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread2 is going on...."); System.out.println("thread2 is over!!!"); } } }}

運行效果:

enter thread1...thread1 is waiting...enter thread2....thread2 is sleep....thread2 is going on....thread2 is over!!!thread1 is going on ....thread1 is over!!!

如果注釋掉代碼TestD.class.notify()的運行效果:

enter thread1...thread1 is waiting...enter thread2....thread2 is sleep....thread2 is going on....thread2 is over!!!
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新丰县| 琼中| 贺兰县| 高邑县| 突泉县| 普定县| 高唐县| 水城县| 汾阳市| 定兴县| 寿阳县| 长沙市| 仙桃市| 高密市| 潜山县| 三都| 南川市| 安义县| 达尔| 蒙阴县| 江华| 萝北县| 秦皇岛市| 广安市| 昭通市| 大厂| 循化| 岚皋县| 井冈山市| 巴马| 杭锦旗| 唐海县| 成安县| 中方县| 塔河县| 堆龙德庆县| 屯门区| 司法| 通城县| 上思县| 尉氏县|