欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生产者和消费者

程序员文章站 2022-07-12 17:41:43
...
package java.thread;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/27.
 */
public class ProducerConsumerDemo {
	public static void main(String[] args) {
		Pool p = new Pool();
		Producer p1 = new Producer("p1",p);
		Producer p2 = new Producer("p2",p);
		Consumer c1 = new Consumer("c1" , p);
		p1.start();
		p2.start();
		c1.start();
	}
}

/**
 * 池子
 */
class Pool{
	private int MAX = 100 ;
	private List<Integer> list = new LinkedList<Integer>();

	/**
	 *
	 * @param i
	 */
	public synchronized void add(Integer i){
		while(list.size() >= MAX){
			try {
				this.wait();
				System.out.println("xxx");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		list.add(0, i);
		this.notify();
	}

	/**
	 * 剪切
	 */
	public synchronized Integer remove(){
		while(list.isEmpty()){
			try {
				this.wait();
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}
		Integer i = list.remove(0);
		this.notify();
		return i ;
	}
}

/**
 * 生产者
 */
class Producer extends Thread{

	private static int index = 0 ;

	private String name0;
	private Pool pool ;

	public Producer(String name0 ,Pool pool) {
		this.pool = pool;
		this.name0 = name0 ;
	}

	public void run() {
		while(true){
			int tmp = index ;
			index ++ ;
			pool.add(tmp);
			System.out.println(name0 + " produced : " + tmp );
		}
	}
}

/**
 * 消费者
 */
class Consumer extends Thread{

	private String name0 ;

	private static int index = 0 ;
	private Pool pool ;

	public Consumer(String name0 ,Pool pool) {
		this.pool = pool;
		this.name0 = name0 ;
	}

	public void run() {
		while(true){
			Integer i = pool.remove();
			if(i != null){
				System.out.println(name0 + " consumed : " + i);
			}
		}
	}
}

相关标签: 生产者 消费者