使用阻塞队列BlockingQueue实现生产者消费者

当缓冲区(资源存储)为空时,消费者阻塞等待;

当缓冲区满了时,生产者阻塞等待; 

package test;

import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**  
* @author sgs  
* @date 2018年7月27日    
*/
public class test1 {
	
	
	public static void main(String[] args) throws InterruptedException {
		// 创建阻塞队列
		LinkedBlockingDeque linkedBlockingDeque = new LinkedBlockingDeque<>();
		Producer p1 = new Producer(linkedBlockingDeque);
        Producer p2 = new Producer(linkedBlockingDeque);
        Producer p3 = new Producer(linkedBlockingDeque);
        Consumer c1 = new Consumer(linkedBlockingDeque);
        Consumer c2 = new Consumer(linkedBlockingDeque);
        Consumer c3 = new Consumer(linkedBlockingDeque);
        // 创造线程池
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(p1);
        service.execute(p2);
        service.execute(p3);
        service.execute(c1);
        service.execute(c2);
        service.execute(c3);
        Thread.sleep(1000);
        p1.stop();
        p2.stop();
        p3.stop();
        Thread.sleep(3000);
        // 停止线程池工作,已有的线程完成后结束
        service.shutdown();
	}
	
	
}

// 生产者
class Producer implements Runnable{
	// 运行标识
	private volatile boolean isRunning = true;
	// 内存缓冲区
    private BlockingQueue blockingQueue;
    // 总数 原子操作
    private static AtomicInteger count = new AtomicInteger();
    // 睡眠时间
    private static final int SLEEPTIME = 1000;
    
    public Producer(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }
    
	@Override
	public void run() {
		// 生成随机数
		Random random = new Random();
		abc abc = null;
		try {
			while (isRunning) {
				System.out.println("生产者 NAME: " + Thread.currentThread().getName() +"  ID:"+ Thread.currentThread().getId());
				Thread.sleep(random.nextInt(SLEEPTIME));
				abc = new abc();
							// 以原子方式将当前值加 1
				abc.setAge(count.incrementAndGet());
				System.out.println("生产者:" + abc.getAge() );
				// 如果超时(blockingQueue.offer)超过2秒
				if(!blockingQueue.offer(abc, 2, TimeUnit.SECONDS)) {
					System.out.println(abc + "超时");
				}
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void stop() {
        isRunning = false;
    }
}

 // 消費者
class Consumer implements Runnable{
	private BlockingQueue blockingQueue;
    private static final int SLEEPTIME = 1000;
    
    public Consumer(BlockingQueue blockingQueue){
        this.blockingQueue = blockingQueue;
    }
	
	
	@Override
	public void run() {
		System.out.println("消费者NAME :" + Thread.currentThread().getName() +"  ID:"+ Thread.currentThread().getId());
		 Random r = new Random();
	        try{
	            while(true){
	            	// 移除阻塞(take())
	            	abc abc = blockingQueue.take();
	                if(abc != null)
	                {
	                    int age = abc.getAge();
	                    // MessageFormat.format格式化消息,根据{}填写数据
	                    // System.out.println(MessageFormat.format("{0}",age));
	                    System.out.println("消费者:" + age);
	                    Thread.sleep(r.nextInt(SLEEPTIME));
	                }
	            }
	        }catch (InterruptedException e) {
	            e.printStackTrace();
	            Thread.currentThread().interrupt();
	        }
	}
	
}

class abc{
	private Integer age;

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	
}

 

你可能感兴趣的:(使用阻塞队列BlockingQueue实现生产者消费者)