1. 程式人生 > >Java多線程——wait方法和notify方法的詳解

Java多線程——wait方法和notify方法的詳解

執行 註意 2.0 消費 如果 鎖對象 16px not 線程池

wait():等待,如果線程執行了wait方法,那麽該線程會進入等待的狀態,等待狀態下的線程必須要被其他線程調用notify()方法才能喚醒。

notify():喚醒,喚醒線程池等待線程其中的一個。

notifyAll():喚醒線程池所有等待線程。

wait與notify方法要註意的事項:

1. wait方法與notify方法是屬於Object對象的。

2. wait方法與notify方法必須要在同步代碼塊或者是同步函數中才能使用。

3. wait方法與notify方法必須要由所對象調用。

消費者與生產者例子:

生產者:
public void run() {
  int i = 0 ;


  while(true){
    synchronized (p) {
      if(p.flag==false){
        if(i%2==0){
          p.name = "蘋果";
          p.price = 6.5;
        }else{
          p.name="香蕉";
          p.price = 2.0;
        }
        System.out.println("生產者生產出了:"+ p.name+" 價格是:"+ p.price);

        p.flag = true;
        i++;
        p.notifyAll(); //喚醒消費者去消費
      }else{
        //已經生產 完畢,等待消費者先去消費
        p.wait(); //生產者等待

      }

消費者:
public void run() {
  while(true){
    synchronized (p) {
      if(p.flag==true){ //產品已經生產完畢
        System.out.println("消費者消費了"+p.name+" 價格:"+ p.price);


        p.flag = false;
        p.notifyAll(); // 喚醒生產者去生產
      }else{
        //產品還沒有生產,應該 等待生產者先生產。
        p.wait(); //消費者也等待了...
      }

在這段代碼中鎖對象為p,

wait():一個線程如果執行了wait方法,那麽該線程就會進去一個以鎖對象為標識符的線程池中等待。

在生產者與消費者代碼中,線程執行了wait方法會進入以p為標識符的線程池中等待

notify():如果一個線程執行了notify方法,那麽就會喚醒以鎖對象為標識符的線程池中等待線程中其中一個。

Java多線程——wait方法和notify方法的詳解