多消费者,多生产者模式Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZHJUNJUN93/article/details/78583557

一种实现方式(自己控制线程池)

package com.java.test;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class ProducerConsumerDemo {

    public static void main(String[] args) {

        BlockingQueue<Integer> shareQueue = new LinkedBlockingDeque<Integer>();

        Thread prodThread1 = new Thread(new Producer(shareQueue, 1));
        Thread prodThread2 = new Thread(new Producer(shareQueue, 2));
        Thread consuThread1 = new Thread(new Consumer(shareQueue, 1));
        Thread consuThread2 = new Thread(new Producer(shareQueue, 2));

        prodThread1.start();
        prodThread2.start();
        consuThread1.start();
        consuThread2.start();
    }
}
class Producer implements Runnable {

    private final BlockingQueue<Integer> sharedQueue;
    private int threadNo;

    public Producer(BlockingQueue<Integer> sharedQueue, int threadNo) {
        this.threadNo = threadNo;
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        for (;;) {
            try {
                int number = new Double(Math.random()*10).intValue() + (10 * threadNo);
                System.out.println("Producted:" + number + ":by thread:" + threadNo);
                sharedQueue.put(number);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {
    private final BlockingQueue<Integer> sharedQueue;
    private int threadNo;

    public Consumer(BlockingQueue<Integer> sharedQueue, int threadNo) {
        this.threadNo = threadNo;
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                int num = sharedQueue.take();
                System.out.println("Consumed: " + num + ":by thread:" + threadNo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

用线程池的实现方式

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ProducerConsumerDemo {

    public static void main(String[] args) {
        try {
            Broker broker = new Broker();
            ExecutorService threadPool = Executors.newFixedThreadPool(3);
            threadPool.execute(new Consumer("1", broker));
            threadPool.execute(new Consumer("2", broker));
            Future producerStatus = threadPool.submit(new Producer(broker));
            // this will wait for the producer to finish its execution.
            producerStatus.get();

            threadPool.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Producer implements Runnable {

    private Broker broker;

    public Producer(Broker broker) {
        this.broker = broker;
    }

    @Override
    public void run() {
        try {
            for (Integer i = 1; i < 50 + 1; ++i) {
                System.out.println("Producer produced: " + i);
                Thread.sleep(100);
                broker.put(i);
            }

            this.broker.continueProducing = Boolean.FALSE;
            System.out.println("Producer finished its job; terminating.");
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    }

}

class Consumer implements Runnable {
    private String name;
    private Broker broker;

    public Consumer(String name, Broker broker) {
        this.name = name;
        this.broker = broker;
    }

    @Override
    public void run() {
        try {
            Integer data = broker.get();

            while (broker.continueProducing || data != null) {
                Thread.sleep(1000);
                System.out
                        .println("Consumer " + this.name + " processed data from broker: " + data);

                data = broker.get();
            }

            System.out.println("Comsumer " + this.name + " finished its job; terminating.");
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

class Broker {
    public ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(100);
    public Boolean continueProducing = Boolean.TRUE;

    public void put(Integer data) throws InterruptedException {
        this.queue.put(data);
    }

    public Integer get() throws InterruptedException {
        return this.queue.poll(1, TimeUnit.SECONDS);
    }
}

用传统的多线程的方式解决

public class ProducerConsumerTest {
   public static void main(String[] args) {
      CubbyHole c = new CubbyHole();
      Producer p1 = new Producer(c, 1);
      Consumer c1 = new Consumer(c, 1);
      p1.start(); 
      c1.start();
   }
}

class CubbyHole {
   private int contents;
   private boolean available = false;

   public synchronized int get() {
      while (available == false) {
         try {
            wait();
         } catch (InterruptedException e) {}
      }
      available = false;
      notifyAll();
      return contents;
   }
   public synchronized void put(int value) {
      while (available == true) {
         try {
            wait();
         } catch (InterruptedException e) { } 
      }
      contents = value;
      available = true;
      notifyAll();
   }
}

// Consumer
class Consumer extends Thread {

   private CubbyHole cubbyhole;
   private int number;

   public Consumer(CubbyHole c, int number) {
      cubbyhole = c;
      this.number = number;
   }
   public void run() {
      int value = 0;
      for (int i = 0; i < 10; i++) {
         value = cubbyhole.get();
         System.out.println("Consumer #" + this.number + " got: " + value);
      }
   }
}

// Producer
class Producer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   public Producer(CubbyHole c, int number) {
      cubbyhole = c;
      this.number = number;
   } 
   public void run() {
      for (int i = 0; i < 10; i++) {
         cubbyhole.put(i);
         System.out.println("Producer #" + this.number + " put: " + i);
         try {
            sleep((int)(Math.random() * 100));
         } catch (InterruptedException e) { }
      } 
   }
} 

猜你喜欢

转载自blog.csdn.net/ZHJUNJUN93/article/details/78583557
今日推荐