生产者消费者模式实现

生产者与消费者解耦,典型应用:MQ。不多解释,code talking:


调用模块:

package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class Run {
	public static void main(String[] args) {
		BlockingDeque<Integer> queue = new LinkedBlockingDeque<Integer>(50);
		int stopConditon = 100;
		new Productor(queue).begin(stopConditon);
		new Customer(queue).begin(stopConditon);
		
	}
}


生产者模块:

 

package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class Productor {
	static AtomicInteger flag = new AtomicInteger(0);
	private BlockingDeque<Integer> queue;

	public Productor(BlockingDeque<Integer> queue) {
		this.queue = queue;
	}

	public void begin(int stopConditon) {
		new Thread(new Create(queue, stopConditon)).start();
	}

	public static class Create implements Runnable {
		private BlockingDeque<Integer> queue;
		private int stopConditon;

		public Create(BlockingDeque<Integer> queue, int stopConditon) {
			this.queue = queue;
			this.stopConditon = stopConditon;
		}

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(5);
					int i = flag.incrementAndGet();
					if (i == stopConditon) {
						queue.put(i);
						System.out.println("stop put element >>> ");
						break;
					}
					queue.put(i);
					System.out.println("put element >>> " + i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}


消费者模块

package com.array7.ds.pc;

import java.util.concurrent.BlockingDeque;

public class Customer {
	BlockingDeque<Integer> queue;

	public Customer(BlockingDeque<Integer> queue) {
		this.queue = queue;
	}

	public void begin(int stopConditon) {
		new Thread(new Get(queue, stopConditon)).start();
	}

	public static class Get implements Runnable {
		private BlockingDeque<Integer> queue;
		private int stopConditon;

		public Get(BlockingDeque<Integer> queue, int stopConditon) {
			this.queue = queue;
			this.stopConditon = stopConditon;
		}

		@Override
		public void run() {
			while (true) {
				try {

					Thread.sleep(10);
					Integer e = queue.take();
					if (e != null) {
						if (e.intValue() == stopConditon) {
							System.out.println("stop get element >>>>>> ");
							break;
						}
						System.out.println("get element >>>>>> " + e);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2015-06-10 13:21  土豆条  阅读(195)  评论(0编辑  收藏  举报