欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年10月09日 08:38:16   投稿:laozhang  
本篇文章給大家分享了關(guān)于Java中線程的等待與喚醒的知識點內(nèi)容,有需要的朋友們可以學習下。

我們先來看一下實例代碼:

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 {
        // 啟動“線程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

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

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

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整除時,休眠100毫秒
            if (i%4 == 0)
              Thread.sleep(100);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    } 
  } 
}

相關(guān)文章

最新評論