JAVA多线程(五)用lock、synchronized、阻塞队列三种方法实现生产者消费者模式

这篇博客算是上一篇JAVA多线程(三)生产者消费者模式及实现方法的补充。用三种方法(lock、synchronized、阻塞队列)实现生产者消费者模式。具体内容是:生产者产生随机数(为了方便阅读结果,我把随机数限定在10以内的整数),消费者读取并打印。

1 阻塞队列实现生产者消费者模式

阻塞队列是最简单的实现方法

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Random;

public class BlockingQueuePattern {

    public static void main(String args[]){

     //阻塞队列
     BlockingQueue sharedQueue = new LinkedBlockingQueue();

     //创建生产者线程和消费者线程
     Thread prodThread = new Thread(new Producer(sharedQueue));
     Thread consThread = new Thread(new Consumer(sharedQueue));

     //启动生产者线程和消费者线程
     prodThread.start();
     consThread.start();
    }
}

//生产者类
class Producer implements Runnable {

    private final BlockingQueue sharedQueue;

    public Producer(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        for(int i=0; i<10; i++){
            try {
                //产生10以内的随机整数放入阻塞队列
                Random random = new Random();
                int ProdRandom=random.nextInt(10);
                System.out.println("Produced: " + ProdRandom);
                sharedQueue.put(ProdRandom);
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

//消费者类
class Consumer implements Runnable{

    private final BlockingQueue sharedQueue;

    public Consumer (BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        while(true){
            try {
                System.out.println("Consumed: "+ sharedQueue.take());
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
} 
Output:
Produced: 4
Produced: 7
Produced: 8
Consumed: 4
Consumed: 7
Produced: 6
Consumed: 8
Consumed: 6
Produced: 1
Produced: 7
Consumed: 1
Consumed: 7
Produced: 3
Produced: 5
Consumed: 3
Consumed: 5
Produced: 9
Produced: 7
Consumed: 9
Consumed: 7

2 lock实现生产者消费者模式

既然不用JAVA提供给我们的现成的阻塞队列,我们不如自己创建一个队列,代码如下:

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OptimisticLockPattern {
    public static void main(String[] args){     
         SelfQueue selfqueue = new SelfQueue();

         //创建生产者线程和消费者线程
         Thread prodThread = new Thread(new Producer(selfqueue));
         Thread consThread = new Thread(new Consumer(selfqueue));

         //启动生产者线程和消费者线程
         prodThread.start();
         consThread.start();
    }
}


class SelfQueue{
    int max = 5;
    LinkedList<Integer> ProdLine = new LinkedList<Integer>();
    Lock lock = new ReentrantLock(); 
    Condition full = lock.newCondition();  
    Condition empty = lock.newCondition();

    public void produce(int ProdRandom){       
        try {
            lock.lock();
            while(max == ProdLine.size()){
                System.out.println("存储量达到上限,请等待");
                full.await();
            }
            ProdLine.add(ProdRandom);
            empty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    } 

    public int consume(){  
        int m = 0;
        try {
            lock.lock();
            while(ProdLine.size() == 0){
                System.out.println("队列是空的,请稍候");
                empty.await();
            }
            m = ProdLine.removeFirst();
            full.signal(); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
            return m;
        }
    }
}

//生产者
class Producer implements Runnable{
    private final SelfQueue selfqueue;

    public Producer(SelfQueue selfqueue) {
          this.selfqueue = selfqueue;
    }

    public void run() {
      for (int i = 0; i < 10; i++) {
            Random random = new Random();
            int ProdRandom=random.nextInt(10);
            System.out.println("Produced: " + ProdRandom);
            selfqueue.produce(ProdRandom);          
      }
  }
}

//消费者
class Consumer implements Runnable{
    private final SelfQueue selfqueue;

    public Consumer(SelfQueue selfqueue) {
          this.selfqueue = selfqueue;
    }

    public void run() {
      while(true) {
              System.out.println("Consumed: "+ selfqueue.consume());
      }
  }
}
Output:
Produced: 1
Produced: 9
Consumed: 1
Consumed: 9
队列是空的,请稍候
Produced: 9
Produced: 1
Consumed: 9
Produced: 8
Consumed: 1
Consumed: 8
队列是空的,请稍候
Produced: 6
Produced: 8
Consumed: 6
Produced: 4
Consumed: 8
Produced: 4
Consumed: 4
Produced: 0
Consumed: 4
Consumed: 0
队列是空的,请稍候

3 synchronized实现生产者消费者模式

synchronized不需要自己手动解锁,这里用到了前面提过的wait()&notify()方法。

import java.util.Random;

public class PessimisticLockPattern {
    public static void main(String[] args){     
         SelfQueue selfqueue = new SelfQueue();

         //创建生产者线程和消费者线程
         Thread prodThread = new Thread(new Producer(selfqueue));
         Thread consThread = new Thread(new Consumer(selfqueue));

         //启动生产者线程和消费者线程
         prodThread.start();
         consThread.start();
    }
}


class SelfQueue{
    int index = 0; 
    int[] ProdLine = new int[6];

    public synchronized void produce(int ProdRandom){
        while(index == ProdLine.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        ProdLine[index] = ProdRandom;
        index++;
    }

    public synchronized int consume(){
        while(index == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        return ProdLine[index];
    }
}

//生产者
class Producer implements Runnable{
    private final SelfQueue selfqueue;

    public Producer(SelfQueue selfqueue) {
        this.selfqueue = selfqueue;
  }

  public void run() {
    for (int i = 0; i < 10; i++) {
            Random random = new Random();
            int ProdRandom = random.nextInt(10);
        System.out.println("Produced: " + ProdRandom);
            selfqueue.produce(ProdRandom);          
    }
}
}

//消费者
class Consumer implements Runnable{
    private final SelfQueue selfqueue;

  public Consumer(SelfQueue selfqueue) {
        this.selfqueue = selfqueue;
  }

  public void run() {
    while(true) {
          System.out.println("Consumed: "+ selfqueue.consume());
    }
}
}
Output:
Produced: 3
Produced: 3
Consumed: 3
Produced: 8
Produced: 3
Consumed: 3
Produced: 2
Produced: 6
Consumed: 3
Produced: 7
Produced: 8
Produced: 1
Produced: 9
Consumed: 6
Consumed: 9
Consumed: 1
Consumed: 8
Consumed: 7
Consumed: 2
Consumed: 8

你可能感兴趣的:(多线程,生产者消费者)