亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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

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

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

實(shí)現(xiàn)生產(chǎn)者和消費(fèi)者模式  倉(cāng)庫(kù)容量為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)者線(xià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)" + "---庫(kù)存" + arrayList.size());
        arrayList.notify();
      }
    }
  }
}

//消費(fèi)者線(xiàn)程
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)" + "---庫(kù)存" + arrayList.size());
        arrayList.notify();
      }
    }
  }
}

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

相關(guān)文章

最新評(píng)論