多线程,生产者消费者

备注:来自小可08年的纸笔记,因为纸张快烂了,故此誊抄于此,以备不时只需,有的代码菜到几点,仅供娱乐。

 

package nie.test.util.thread;

import java.util.List;
import java.util.Vector;

/** 多线程之 生产者消费者 一种
 * @author niewj
 */
public class TestMultiThread {
	public static void main(String[] args) {
		MyContainer container = new MyContainer();
		
		
		Producer p = new Producer(container);
		Consumer c = new Consumer(container);
		
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
	}
}
class MyContainer{
	List<Object> lst = new Vector<Object>(); //承载容器
	boolean flag = true;	//标识位,默认为:无产品,可以生产了
	
	/** 生产
	 * @param obj
	 * @throws InterruptedException
	 */
	synchronized public void push(Object obj) throws InterruptedException{
		while(!flag){
			wait();
		}
		lst.add(obj);
		System.out.println("Produce One: "+obj);
		flag = false;
		notifyAll();
	}

	/** 消费
	 * @return
	 * @throws InterruptedException
	 */
	synchronized public Object pop() throws InterruptedException{
		Object obj = null;
		while(flag){
			wait();
		}
		if(!lst.isEmpty()){
			obj = lst.remove(0);
			System.out.println("Consum One: "+obj);
			flag = true;
			notifyAll();
		}else{
			obj=null;
		}
		return obj;
	}
}

class Consumer implements Runnable{
	MyContainer con;
	
	/** 初始化消费者的 容器 ,同生产者用同一个
	 * @param con
	 */
	public Consumer(MyContainer con) {
		this.con = con;
	}
	
	@Override
	public void run() {
		while(true){
			try {
				Object obj = con.pop();
				System.out.println(obj+" 被消费!");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Producer implements Runnable{
	MyContainer con;
	
	/** 初始化生产者 用到的 容器,同消费者用同一个
	 * @param con
	 */
	public Producer(MyContainer con) {
		this.con = con;
	}
	
	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(1000);
				Object obj = new Integer((int)(Math.random()*1000));;	//产品
				con.push(obj);
				System.out.println(obj+" 被生产出来!");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值