利用阻塞队列BlockingDeque实现生产者-消费者模式

阅读更多
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 消费者类
 * */
public class Consumer implements Runnable {
	private BlockingDeque queue = new LinkedBlockingDeque();
	
	public Consumer(BlockingDeque queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int i = 0;
			do{
				try {
					String product = queue.take();
					if(!"".equals(product) && null != product){
						System.out.println("消费者-:"+product);
						i++;
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
			}while(i < 50);
		}
}

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
/**
 * 生产者类
 * */

public class Producer implements Runnable {
	private BlockingDeque queue = new LinkedBlockingDeque();
	
	public Producer(BlockingDeque queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0; i < 50; i++){
			try {
				System.out.println("生产者-Product"+i);
				queue.put("Prodect:"+i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

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

/**
 * 测试类
 * */
public class BlockingQueueTest {
	
	private static BlockingDeque queue = new LinkedBlockingDeque();
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Producer producer = new Producer(queue);
		Consumer cusumer = new Consumer(queue); 
		new Thread(cusumer).start();
		new Thread(producer).start();
	}
}

你可能感兴趣的:(java,BlockingDeque,并发编程,生产者,消费者)