java自带API实现生产者消费者模式

通过JDK自带的BlockingQueue来实现生产者与消费者模式

①生产者

package org.fenxisoft.quence;

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable{
    private BlockingQueue<Integer> queue;
    private int count;
	Producer(BlockingQueue<Integer> queue, int count){
		this.queue = queue;
		this.count = count;
	}
	@Override
	public void run() {
		try {
			for(int i =0; i < count; i++){
				/**
				 * 如果队列满了,则会阻塞
				 * 将指定的元素插入此队列的尾部,如果该队列已满,则等待可用的空间
				 */
				queue.put(i);
				System.out.println("生产者生产数据:"+i);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

②消费者

package org.fenxisoft.quence;

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{

	private BlockingQueue<Integer> queue;
	private int count;
	Consumer(BlockingQueue queue, int count){
		this.queue = queue;
		this.count = count;
	}
	
	@Override
	public void run() {
		
		try {
			for(int i =0; i<count; i++){
				/**
				 * 如果队列为空,则会阻塞
				 * 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)
				 */
				Integer in= queue.take();
				System.out.println("消费者消费数据:"+in);
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	
	

}

 ③测试类

package org.fenxisoft.quence;

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

public class BlockingQuenceTest {
	
	public static final int MAX_VALUE = 100;
	
	public static void main(String[] args) {
		
		/**
		 * 创建线程池
		 */
		ExecutorService service = Executors.newCachedThreadPool();
		
		BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(10);
		
		Producer producer = new Producer(blockingQueue, MAX_VALUE);
		Consumer consumer = new Consumer(blockingQueue, MAX_VALUE);
		
		service.submit(producer);
		service.submit(consumer);
		
		service.shutdown();
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值