使用BlockingQueue实现生产者/消费者案例

生产者线程

package date0805.demo2;

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

public class Producer implements Runnable {

	private BlockingQueue<Integer> queue;
	private Random r=new Random();
	public Producer(BlockingQueue<Integer> queue) {
		super();
		this.queue = queue;
	}

	@Override
	public void run() {
		
		try {
			while(true) {
				queue.put(produce());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

	private Integer produce() throws InterruptedException {
		
		Random random = new Random();
		int i = random.nextInt(100);
		Thread.sleep(r.nextInt(2000));
		String tips="线程"+Thread.currentThread().getId()+"生产了"+i;
		System.out.println(tips);
		return i;
		
	}
}



消费者线程

package date0805.demo2;

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

public class Consumer implements Runnable {

	private BlockingQueue<Integer> queue;
	private Random r=new Random();
	public Consumer(BlockingQueue<Integer> queue) {
		super();
		this.queue = queue;
	}

	@Override
	public void run() {
		
		try {
			while(true) {
				consume(queue.take());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void consume(Integer i) throws InterruptedException {
		Thread.sleep(r.nextInt(2000));
		String tips="线程"+Thread.currentThread().getId()+"消费了"+i;
		System.out.println(tips);
	}
}



客户端代码

package date0805.demo2;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Test {

	public static void main(String[] args) {

		BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
		Producer producer = new Producer(queue);
		Consumer consumer1 = new Consumer(queue);
		Consumer consumer2 = new Consumer(queue);
		Consumer consumer3 = new Consumer(queue);
		Consumer consumer4 = new Consumer(queue);
		new Thread(producer).start();
		new Thread(consumer1).start();
		new Thread(consumer2).start();
		new Thread(consumer3).start();
		new Thread(consumer4).start();
	}
}

运行结果:

线程10生产了54
线程10生产了99
线程11消费了54
线程12消费了99
线程10生产了69
线程10生产了90
线程13消费了69
线程10生产了80
线程10生产了66
线程14消费了90
线程12消费了66
线程10生产了93
线程11消费了80
线程13消费了93
线程10生产了84
线程14消费了84
线程10生产了98
线程12消费了98
线程10生产了87
线程10生产了85
线程13消费了85




你可能感兴趣的:(生产者,消费者)