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

首頁 > 開發(fā) > Java > 正文

代碼分析Java中線程的等待與喚醒

2024-07-14 08:42:28
字體:
供稿:網(wǎng)友

我們先來看一下實(shí)例代碼:

class ThreadA extends Thread{   public ThreadA(String name) {    super(name);  }   public void run() {    synchronized (this) {      System.out.println(Thread.currentThread().getName()+" call notify()");      notify();    }  }}public class WaitTest {  public static void main(String[] args) {    ThreadA t1 = new ThreadA("t1");    synchronized(t1) {      try {        // 啟動(dòng)“線程t1”        System.out.println(Thread.currentThread().getName()+" start t1");        t1.start();         // 主線程等待t1通過notify()喚醒。        System.out.println(Thread.currentThread().getName()+" wait()");        t1.wait();         System.out.println(Thread.currentThread().getName()+" continue");      } catch (InterruptedException e) {        e.printStackTrace();      }    }  }}

輸出結(jié)果:main start t1 -> main wait() -> t1 call notify() -> main continue

其實(shí)調(diào)用t1.start(),t1為就緒狀態(tài),只是main方法中,t1被main線程鎖住了,t1.wait()的時(shí)候,讓當(dāng)前線程等待,其實(shí)是讓main線程等待了,然后釋放了t1鎖,t1線程執(zhí)行,打印t1 call notify(),然后喚醒main線程,最后結(jié)束;

這里說一下wait()與sleep()的區(qū)別,他們的共同點(diǎn)都是讓線程休眠,但是wait()會(huì)釋放對(duì)象同步鎖,而sleep()不會(huì);下面的代碼t1結(jié)束之后才會(huì)運(yùn)行t2;能夠證實(shí)這一點(diǎn);

public class SleepLockTest{   private static Object obj = new Object();  public static void main(String[] args){     ThreadA t1 = new ThreadA("t1");     ThreadA t2 = new ThreadA("t2");     t1.start();     t2.start();  }   static class ThreadA extends Thread{    public ThreadA(String name){       super(name);     }     public void run(){       synchronized (obj) {        try {          for(int i=0; i <10; i++){             System.out.printf("%s: %d/n", this.getName(), i);             // i能被4整除時(shí),休眠100毫秒            if (i%4 == 0)              Thread.sleep(100);          }        } catch (InterruptedException e) {          e.printStackTrace();        }      }    }   } }


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到JAVA教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 清水河县| 武陟县| 宽城| 锡林郭勒盟| 万载县| 吉林省| 屏边| 西安市| 白河县| 咸阳市| 鹿泉市| 新干县| 汽车| 行唐县| 马鞍山市| 西安市| 锡林浩特市| 射阳县| 栾川县| 颍上县| 包头市| 南宫市| 分宜县| 井研县| 汉源县| 宜章县| 英超| 大理市| 嵊泗县| 海宁市| 鄂尔多斯市| 读书| 宝清县| 泰州市| 石棉县| 安阳市| 治多县| 德钦县| 三原县| 河津市| 瓦房店市|