用BlockingQueue实现简单的生产者-消费者模型

时间:2020-12-16 17:39:45

package com.example.test;

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

/**
 * 用BlockingQueue实现生产者消费者
 * @author 宋小亮
 *
 */
public class ArrayBlockingQueueTest {
  
 private static int capacity = 10;//设置阻塞队列的大小
 private static ArrayBlockingQueue<Person> queue =  new ArrayBlockingQueue<>(capacity);
 
 public static void main(String[] args){
  
  //创建两个生产者线程
    for (int i = 0; i < 2; i++) {
      new Thread(new Producer(queue)).start();
      new Thread(new Producer(queue)).start();
     }
   //创建一个消费者线程
    for (int i = 0; i < 3; i++) {
      new Thread(new Customer(queue)).start();
   

      }
 
 }
}

//实体类
class Person{
 private String name;
}

//生产者
class Producer implements Runnable{
 private BlockingQueue<Person> queue;
 public Producer(BlockingQueue<Person> queue){
  this.queue = queue;
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(true){
   produce();
  }
 }
 public void produce(){
  Person person = new Person();
  try {
   queue.put(person);
   System.out.println("Producer:"+person);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

//消费者
class Customer implements Runnable{

 private BlockingQueue<Person> queue;
 
 public Customer(BlockingQueue<Person> queue){
  this.queue = queue;
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(true){
   customer();
  }
 }
 
 public void customer(){
  Person person;
  try {
   person = queue.take();
   System.out.println("Customer:"+person);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}