生产者和消费者

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);
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值