如何实现ArrayBlockingQueue?

时间:2014-04-15 17:18:21

标签: java multithreading thread-safety

以下代码是经典的制作人/消费者问题。

代码运行正常,但使用起来仍然非常繁琐。我需要实现一个ArrayBlockingQueue,但我不确定如何这样做,以使程序成为线程安全。

非常感谢任何帮助。

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer{
  private static int NUM_MESSAGES = 3;
  private static int NUM_PRODUCERS = 5;
  private static int NUM_CONSUMERS = 5;

  public static void main(String[] args) throws InterruptedException{
    Queue<String> buffer = new LinkedList<String>();

    Thread[] producers = new Thread[NUM_PRODUCERS];
    for(int i=0; i<NUM_PRODUCERS; i++){
      producers[i] = new Producer("producer"+i, buffer);
      producers[i].start();
    }

    Thread[] consumers = new Thread[NUM_CONSUMERS];
    for(int i=0; i<NUM_CONSUMERS; i++){
      consumers[i] = new Consumer("consumer"+i, buffer);
      consumers[i].start();
    }

    for(int i=0; i<NUM_PRODUCERS; i++){
      producers[i].join();
    }

    for(int i=0; i<NUM_CONSUMERS; i++){
      consumers[i].join();
    }

    System.err.println("messages left in buffer:");
    while(!buffer.isEmpty()){
      System.err.println(buffer.remove());
    }
  }

   public static class Producer extends Thread{
     Queue<String> buffer;

    public Producer(String name, Queue<String> newBuffer){
      super(name);
      buffer = newBuffer;
    }

    public void run(){
      for (int i=0; i<NUM_MESSAGES; i++){
        String message = "message "+i+" from thread "+getName();
        buffer.add(message);
        System.err.println("sent "+message);
        try{
          Thread.sleep((long)(Math.random()*10));
        }catch(InterruptedException e){}
      }
    }
  }

  public static class Consumer extends Thread{
    Queue<String> buffer;

    public Consumer(String name, Queue<String> newBuffer){
      super(name);
      buffer = newBuffer;
    }

    public void run(){
      int count = 0;  
      while (count < NUM_MESSAGES){
        String message;
        if(!buffer.isEmpty()){
          message = buffer.remove();
          System.err.println(getName()+" received "+message);
          count++;
        }
        try{
          Thread.sleep((long)(Math.random()*10));
        }catch(InterruptedException e){}
      }
    }
  }
}

0 个答案:

没有答案