最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java通過wait()和notifyAll()方法實(shí)現(xiàn)線程間通信

 更新時(shí)間:2017年04月10日 09:04:50   作者:FrankYou  
這篇文章主要為大家詳細(xì)介紹了Java通過wait()和notifyAll()方法實(shí)現(xiàn)線程間通信的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Java實(shí)現(xiàn)線程間通信的具體代碼,供大家參考,具體內(nèi)容如下

Java代碼(使用了2個(gè)內(nèi)部類):

package Threads;

import java.util.LinkedList;

/**
 * Created by Frank
 */
public class ProdCons {
 protected LinkedList<Object> list = new LinkedList<>();
 protected int max;
 protected boolean done = false;

 public static void main(String[] args) throws InterruptedException {
  ProdCons prodCons = new ProdCons(100, 3, 4);
  Thread.sleep(5 * 1000);
  synchronized (prodCons.list) {
   prodCons.done = true;
   try {
    prodCons.notifyAll();
   } catch (Exception ex) {
   }
  }
 }

 private ProdCons(int maxThreads, int nP, int nC) {
  this.max = maxThreads;
  for (int i = 0; i < nP; i++) {
   new Producer().start();
  }
  for (int i = 0; i < nC; i++) {
   new Consumer().start();
  }
 }

 class Producer extends Thread {
  public void run() {
   while (true) {
    Object justProduced = null;
    try {
     justProduced = getObj();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    synchronized (list) {
     while (list.size() == max) {
      try {
       list.wait();
      } catch (InterruptedException e) {
       System.out.println("Producer INTERRUPTED");
      }
     }
     list.addFirst(justProduced);
     list.notifyAll();
     System.out.println("Produced 1;List size now " + list.size());
     if (done) {
      break;
     }
    }
   }
  }
 }

 class Consumer extends Thread {
  public void run() {
   while (true) {
    Object object = null;
    synchronized (list) {
     if (list.size() == 0) {
      try {
       list.wait();
      } catch (InterruptedException e) {
       System.out.println("Consumer INTERRUPTED");
      }
     }
     if (list.size() > 0) {
      object = list.removeLast();
     }
     list.notifyAll();
     System.out.println("List size now " + list.size());
     if (done) {
      break;
     }
    }
    if (null != object) {
     System.out.println("Consuming object " + object);
    }
   }
  }
 }

 private Object getObj() throws InterruptedException {
  Thread.sleep(1000);
  return new Object();
 }
}

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

相關(guān)文章

最新評(píng)論

大名县| 泰州市| 安乡县| 高清| 前郭尔| 西畴县| 武定县| 玛多县| 鹤山市| 永靖县| 分宜县| 晋江市| 华蓥市| 什邡市| 内黄县| 洛浦县| 桐柏县| 苏州市| 甘德县| 瑞金市| 伊宁县| 洛宁县| 鹤庆县| 辽宁省| 共和县| 泰宁县| 股票| 阿拉善盟| 上虞市| 资源县| 建湖县| 吴桥县| 松原市| 乌恰县| 灵璧县| 平阳县| 伽师县| 花垣县| 葫芦岛市| 互助| 龙海市|