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

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

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

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

Java代碼(使用了2個內(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

探索| 巴林左旗| 滨海县| 乌鲁木齐县| 饶平县| 称多县| 绥宁县| 定安县| 黄冈市| 闽清县| 抚顺县| 邯郸县| 滕州市| 邵阳市| 潮州市| 乐陵市| 邢台市| 澄城县| 驻马店市| 海盐县| 盐山县| 石泉县| 任丘市| 普格县| 明光市| 云梦县| 普兰县| 甘南县| 扶绥县| 潼南县| 体育| 定兴县| 清流县| 武威市| 灵山县| 闻喜县| 许昌县| 拉萨市| 德清县| 田林县| 化隆|