标签:nta i++ fixed private object ted ring 基础 容量
一:概念
生产者消费者模式是java并发编程中很经典的并发情况,首先有一个大的容器,生产者put元素到
容器中,消费者take元素出来,如果元素的数量超过容器的容量时,生产者不能再往容器中put元素
,处于阻塞状态,如果元素的数量等于0,则消费者不能在从容器中take数据,处于阻塞状态。
二:示例
/** * */ package com.hlcui.main; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; /** * @author Administrator * */ public class MyQueue { private LinkedList<String> list = new LinkedList<String>(); private AtomicInteger auto = new AtomicInteger(); private int MAX_SIZE; private final int MIN_SIZE = 0; private final Object lock = new Object(); public MyQueue(int mAX_SIZE) { super(); MAX_SIZE = mAX_SIZE; } public void put(String good) { synchronized (lock) { while(list.size()==MAX_SIZE) { try { //如果容器中物品的数量达到上限,那么就阻塞线程 System.out.println("容器已满"); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(good); auto.incrementAndGet(); lock.notify(); } } public String take() { String s = null; synchronized (lock) { while(list.size()==MIN_SIZE) { try { System.out.println("容器已空"); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } s = list.removeFirst(); auto.decrementAndGet(); lock.notify(); } return s; } public int size() { return list.size(); } public static void main(String[] args) { final MyQueue queue = new MyQueue(5); for(int i=0;i<5;i++) { queue.put(i+""); } System.out.println("目前容器中元素数量:"+queue.size()); ExecutorService executors = Executors.newFixedThreadPool(2); executors.execute(new Runnable() { @Override public void run() { for(int i=10;i<20;i++) { queue.put(i+""); System.out.println("添加元素:"+i+""); } } }); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } executors.execute(new Runnable() { @Override public void run() { for(int i=0;i<50;i++) { System.out.println("取出元素:"+queue.take()); } } }); } }
标签:nta i++ fixed private object ted ring 基础 容量
原文地址:http://www.cnblogs.com/warrior4236/p/7532984.html