日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java中怎么實(shí)現(xiàn)線程的等待與喚醒

這篇文章給大家介紹Java中怎么實(shí)現(xiàn)線程的等待與喚醒,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),二道企業(yè)網(wǎng)站建設(shè),二道品牌網(wǎng)站建設(shè),網(wǎng)站定制,二道網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,二道網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(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)于Java中怎么實(shí)現(xiàn)線程的等待與喚醒就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。


名稱欄目:Java中怎么實(shí)現(xiàn)線程的等待與喚醒
瀏覽地址:http://www.dlmjj.cn/article/ppiddi.html