并发线程

LinkedBlockingQueue适用于与生产者消费者模式,并可以限制Queue的大小。有以下特点:
1.在入队列时如果队列已满,则线程阻塞,直到队列有空位置。
2.在出队列时如果无数据,则线程阻塞,直到队列中有数据。

public class TestQueue {
	public static void main(String[] args) {
		LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(1);
		Producer producer1 = new Producer(queue, 1);
		Producer producer2 = new Producer(queue, 2);
		Producer producer3 = new Producer(queue, 3);
		Consumer consumer1 = new Consumer(queue, 1);
		Consumer consumer2 = new Consumer(queue, 2);
		Consumer consumer3 = new Consumer(queue, 3);
		producer1.start();
		producer2.start();
		producer3.start();
		consumer1.start();
		consumer2.start();
		consumer3.start();
	}
}

class Producer extends Thread {
	private static int counter = 0;
	private int id;
	private LinkedBlockingQueue<Integer> productQueue;

	public Producer(LinkedBlockingQueue<Integer> queue, int id) {
		this.productQueue = queue;
		this.id = id;
	}

	public void produce() throws InterruptedException {
		System.out.println("producer " + id + " is waiting for space");
		productQueue.put(++counter);
		System.out.println("producer " + id + " produced: " + counter);
	}

	@Override
	public void run() {
		try {
//			Thread.sleep(5000);
			produce();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Consumer extends Thread {
	private int id;
	private LinkedBlockingQueue<Integer> productQueue;

	public Consumer(LinkedBlockingQueue<Integer> queue, int id) {
		this.productQueue = queue;
		this.id = id;
	}

	public void consume() throws InterruptedException {
		System.out.println("consumer " + id + " is waiting for product..." );
		int value = productQueue.take();
		System.out.println("consumer " + id + " consumed: " + value);
	}

	@Override
	public void run() {
		try {
			Thread.sleep(2000);
			consume();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(并发线程)