生产者和消费者模式

生产者和消费者模式.
核心是生产者(1-n)个和消费者(1-n)个,共同使用同一个队列对象,通过多线程的同步机制等.同一个时间,只有一个生产者或者消费者能向该队列写入消息,或者取出消息(互斥锁)

package com.hgh.java_duoxiancheng.ch3_1.p11;

import java.util.ArrayList;
import java.util.List;

public class MyList {

	public List<String> list = new ArrayList<String>();
	
	synchronized void push(){
		try {
			while (list.size() == 1 ) {
				this.wait();
			}
			list.add("andy string = " + Math.random());
			this.notify();
			System.out.println("pusg=" + list.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	synchronized String pop(){
		String value = "";
		try {
			while (list.size() == 0 ) {
				System.out.println("pop " + Thread.currentThread().getName() + " wait");
				this.wait();
			}
			value = list.get(0);
			list.remove(0);
			this.notify();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
}

package com.hgh.java_duoxiancheng.ch3_1.p11;

public class P {

	private MyList list;
	P(MyList list){
		this.list = list;
	}
	
	public void pushService(){
		list.push();
	}
}

package com.hgh.java_duoxiancheng.ch3_1.p11;

public class C {

	private MyList list;
	C(MyList list){
		this.list = list;
	}
	
	public void popService(){
		list.pop();
	}
}

package com.hgh.java_duoxiancheng.ch3_1.p11;

public class ThreadP extends Thread{

	private P p;
	
	ThreadP(P p){
		this.p = p;
	}
	@Override
	public void run() {
		while (true) {
			p.pushService();
		}

	}
}

package com.hgh.java_duoxiancheng.ch3_1.p11;

public class ThreadC extends Thread{

	private C c;
	
	ThreadC(C c){
		this.c = c;
	}
	@Override
	public void run() {
		while (true) {
			c.popService();
		}

	}
}

package com.hgh.java_duoxiancheng.ch3_1.p11;

public class Run {

	
	/**
	 * 验证生成者和消费者的模式
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		MyList myList = new MyList();
		P p = new P(myList);
		C c = new C(myList);
		ThreadC threadC = new ThreadC(c);
		ThreadP threadP = new ThreadP(p);
		threadP.setName("P");
		threadP.start();
		threadC.setName("C");
		threadC.start();

		
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值