Java核心多线程 -- 消费者生产者Demo一

目的

  实现1个生产者和多个消费者合作工作的模式

手段

  使用wait、notify和synchronized实现线程间同步;使用ConcurrentLinkedQueue同步队列

 

 

生成和消费的pojo类

 

 public class AlarmBookPojo {
	private int iDeviceId;

	public int getiDeviceId() {
		return iDeviceId;
	}

	public void setiDeviceId(int iDeviceId) {
		this.iDeviceId = iDeviceId;
	}
 
	 
	
	
}

 

生产者和消费者同步的队列:

 

 

public class QueueMgr {
	// 同步队列
	ConcurrentLinkedQueue<AlarmBookPojo> queue = new ConcurrentLinkedQueue<AlarmBookPojo>();
	private final static Byte[] synAlarm = new Byte[0]; //同步对象
 
	/**
	 * 返回值有可能为null
	 * @return
	 */
	public AlarmBookPojo get(){
		AlarmBookPojo o = null;
		o = queue.poll();
		
		if(o == null){
			synchronized(synAlarm){
				try {
					synAlarm.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return o;
	}
	
	public boolean put(AlarmBookPojo o){
		boolean bRtn = this.queue.offer(o);
		synchronized(synAlarm){
			synAlarm.notify();
		}
		return bRtn;
	}
	
}

 

 

生产者:

 

public class Productor implements Runnable {
	private QueueMgr queue;
	private int i = 0;
	public Productor(QueueMgr queue){
		this.queue = queue;
	}
	
	public void generate(String sThreadName){
		AlarmBookPojo o = new AlarmBookPojo();
		o.setiDeviceId(i ++ );
		queue.put(o);
		System.out.println(sThreadName + "put pojo.");
	}
	
	public void run(){
		while(true){
			this.generate(Thread.currentThread().getName());
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
 

 

消费者

 

public class Consumer implements Runnable{
	private QueueMgr queue;
	
	public Consumer(QueueMgr queue){
		this.queue = queue;
	}
	
	public void consumer(String sThreadName){
		AlarmBookPojo o = queue.get();
		if(o != null){
			System.out.println(sThreadName + " Comsumer. o = " + o.getiDeviceId());
		}
	}
	
	public void run(){
		while(true){
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			this.consumer(Thread.currentThread().getName());
		}
	}
 
}
 

 

main函数:

 

 

public class Main {
	public static void main(String[] args){
		QueueMgr q = new QueueMgr();
		new Thread(new Consumer(q)).start();
		new Thread(new Productor(q)).start();
//		new Thread(new Productor(q)).start();
//		new Thread(new Productor(q)).start();
		new Thread(new Consumer(q)).start();
		new Thread(new Consumer(q)).start();
	}
}
 

 

 

执行以上程序,正常工作

 

 

Thread-1put pojo.

Thread-1put pojo.

Thread-0 Comsumer. o = 0

Thread-2 Comsumer. o = 1

Thread-1put pojo.

Thread-0 Comsumer. o = 2

Thread-1put pojo.

Thread-3 Comsumer. o = 3

 

 

参考文献

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值