java实现生产者消费者模型
2013-03-13 00:00
513 查看
生产者消费者模型是操作系统中,进程之间同步的比较经典的例子。比较简化的情况是这样的:一个线程产生数据,另一个线程同时消费数据。当缓冲区满时,产生数据的线程暂停。当缓冲区空的时候,消费数据的线程暂停。就这样保持两个线程的同步操作。
贴上代码:
贴上代码:
package com.bupt.test; import java.util.LinkedList; import java.util.List; public class ProducerCustomer { public static void main(String[] args) { Store store = new Store(10); Producer producer = new Producer(store); Customer customer = new Customer(store); new Thread(producer).start(); new Thread(customer).start(); } } class Store{ private List<Integer> products = new LinkedList<Integer>();; private int maxSize; Store(int maxSize){ this.maxSize = maxSize; } private boolean isFull(){ if(products.size() == maxSize){ return true; }else{ return false; } } private boolean isEmpty(){ return products.isEmpty(); } public synchronized void putIn(int i){ if(isFull()){ System.out.println("is full , wait---"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } products.add(new Integer(i)); System.out.println("produce:" + i); notify(); } public synchronized int takeOut(){ if(isEmpty()){ System.out.println("is empty , wait---"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int index = products.size()-1; int temp = products.get(index); products.remove(index); System.out.println("custome:" + temp); notify(); return temp; } } class Producer implements Runnable{ private Store store; public Producer(Store store) { this.store = store; } @Override public void run() { for(int i = 0 ; i < 20 ; i++){ store.putIn((int)(Math.random()*100)); } } } class Customer implements Runnable{ private Store store; public Customer(Store store){ this.store = store; } @Override public void run() { int sum = 0; for(int i = 0 ; i < 20 ; i++){ sum += store.takeOut(); } System.out.println("end---:" + sum/20); } }
相关文章推荐
- 三种方法实现生产者/消费者模型(Java)
- Java多线程15:Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型
- 生产者-消费者模型的java实现
- Java实现生产者消费者模型
- Java实现生产者消费者模型:多线程+BlockingQueue
- java实现生产者消费者模型
- Java实现生产者-消费者模型
- 简单生产者消费者模型(java实现)
- Java多线程15:Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型
- 生产者-消费者模型的Java实现
- Java多线程系列-Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型
- 生产者消费者模型java实现(一)
- JAVA实现多线程生产者消费者模型
- Java多线程15:Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型
- 基于JAVA实现的生产者消费者模型
- 生产者——消费者模型的java代码实现
- Java多线程15:Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型
- Java 多线程学习之生产者消费者模型:一个较完善的实现
- Java---实现生产者消费者模型
- java线程间通信[实现不同线程之间的消息传递(通信),生产者和消费者模型]