java实现生产者消费者模型

生产者消费者模型是操作系统中,进程之间同步的比较经典的例子。比较简化的情况是这样的:一个线程产生数据,另一个线程同时消费数据。当缓冲区满时,产生数据的线程暂停。当缓冲区空的时候,消费数据的线程暂停。就这样保持两个线程的同步操作。

贴上代码:

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实现生产者消费者模型)