JAVA生产者与消费者模式 BlockingQueue与ExecutorService实例

首先创建生产者:

package ProducerAndConsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable {

	private volatile boolean isRunning = true;
	private BlockingQueue queue; // 内存缓冲区
	private static AtomicInteger count = new AtomicInteger();
	// 总数,原子操作
	private static final int SLEEPTIME = 1000;

	public Producer(BlockingQueue queue) {
		this.queue = queue;
	}

	@Override
	public void run() {

		PCData data = null;
		Random r = new Random();
		System.out.println("start producer id=" + Thread.currentThread().getId());
		try {
			while (isRunning) {
				Thread.sleep(r.nextInt(SLEEPTIME));
				data = new PCData(count.incrementAndGet());// 构造任务数据
				System.out.println(data + "is put into queue");
				if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
					// 提交数据到缓冲区中
					System.err.println("failed to put data:" + data);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		isRunning = false;
	}

}
package ProducerAndConsumer;


public class PCData {


	private final int intData;


	public PCData(int d) {
		intData = d;
	}


	public PCData(String d) {
		intData = Integer.valueOf(d);
	}


	public int getData() {
		return this.intData;
	}


	public String toString() {
		return "data:" + intData;
	}
}


消费者

package ProducerAndConsumer;

import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

	private BlockingQueue queue;// 缓冲区
	
	private static final int SLEEPTIME = 1000;

	public Consumer(BlockingQueue queue) {
		this.queue = queue;
	}

	@Override
	public void run() {

		System.out.println("start Consumer id=" + Thread.currentThread().getId());
		Random r = new Random(); // 随机等待时间
		try {

			while (true) {
				PCData data = queue.take();// 提取任务
				if (null != data) {
					int re = data.getData() * data.getData();// 计算平方
					System.out.println(MessageFormat.format("{0}*{1}={2}",
							data.getData(), data.getData(), re));
					Thread.sleep(r.nextInt(SLEEPTIME));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

主函数

package ProducerAndConsumer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {

	public static void main(String[] args) {

		try {
			// 建立缓冲区
			BlockingQueue queue = new LinkedBlockingQueue(10);
			Producer producer1 = new Producer(queue);// 建立生产者
			Producer producer2 = new Producer(queue);
			Producer producer3 = new Producer(queue);

			Consumer consumer1 = new Consumer(queue);// 建立消费者
			Consumer consumer2 = new Consumer(queue);
			Consumer consumer3 = new Consumer(queue);

			ExecutorService service = Executors.newCachedThreadPool();// 建立线程池

			service.execute(producer1);// 运行生产者
			service.execute(producer2);
			service.execute(producer3);

			service.execute(consumer1);// 运行消费者
			service.execute(consumer2);
			service.execute(consumer3);

			Thread.sleep(10 * 1000);

			producer1.stop();// 停止生产者
			producer2.stop();
			producer3.stop();

			Thread.sleep(3000);

			service.shutdown();

		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
运行结果

JAVA生产者与消费者模式 BlockingQueue与ExecutorService实例_第1张图片


你可能感兴趣的:(java)