1. 程式人生 > >用BlockingQueue實現簡單的生產者-消費者模型

用BlockingQueue實現簡單的生產者-消費者模型

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();
  }
 }
}