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

Object類wait及notify方法原理實(shí)例解析

 更新時間:2020年08月20日 10:29:51   作者:javase-->  
這篇文章主要介紹了Object類wait及notify方法原理實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

Object類中的wait和notify方法(生產(chǎn)者和消費(fèi)者模式)  不是通過線程調(diào)用

  • wait():    讓正在當(dāng)前對象上活動的線程進(jìn)入等待狀態(tài),無期限等待,直到被喚醒為止
  • notify():    讓正在當(dāng)前對象上等待的線程喚醒
  • notifyAll():   喚醒當(dāng)前對象上處于等待的所有線程

生產(chǎn)者和消費(fèi)者模式 生產(chǎn)線程和消費(fèi)線程達(dá)到均衡

wait方法和notify方法建立在synchronized線程同步的基礎(chǔ)之上

  • wait方法:   釋放當(dāng)前對象占有的鎖
  • notify方法:   通知,不會釋放鎖

實(shí)現(xiàn)生產(chǎn)者和消費(fèi)者模式  倉庫容量為10

代碼如下

import java.util.ArrayList;

public class Test_14 {
  public static void main(String[] args) {
    ArrayList list = new ArrayList();
    Thread t1 = new Thread(new ProducerThread(list));
    t1.setName("producer");
    Thread t2 = new Thread(new ConsumerThread(list));
    t2.setName("consumer");
    t1.start();
    t2.start();
  }
}
//生產(chǎn)者線程
class ProducerThread implements Runnable{
  private ArrayList arrayList;

  public ProducerThread(ArrayList arrayList) {
    this.arrayList = arrayList;
  }

  @Override
  public void run() {
    while (true) {
      synchronized (arrayList) {
        if (arrayList.size() > 9){
          try {
            arrayList.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        arrayList.add(new Object());
        System.out.println(Thread.currentThread().getName() + "---> 生產(chǎn)" + "---庫存" + arrayList.size());
        arrayList.notify();
      }
    }
  }
}

//消費(fèi)者線程
class ConsumerThread implements Runnable{
  private ArrayList arrayList;

  public ConsumerThread(ArrayList arrayList) {
    this.arrayList = arrayList;
  }

  @Override
  public void run() {
    while (true){
      synchronized (arrayList){
        if (arrayList.size() < 9){
          try {
            arrayList.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        arrayList.remove(0);
        System.out.println(Thread.currentThread().getName() + "---> 消費(fèi)" + "---庫存" + arrayList.size());
        arrayList.notify();
      }
    }
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論