Producer-Consumer模式

java多线程设计模式全部源码:

java多线程设计模式源码

类图

这里写图片描述

时序图

这里写图片描述

  • Main.java
/**
 * 生产者-消费者模式
 * 
 * Main.java用到的java文件如下
 * ProducerThread.java
 * EaterThread.java
 * Table.java用两种实现方式:
 *  1.数组,自己实现同步
 *  2.LinkedList容器,自己实现同步
 *  3.ArrayBlockingQueue自带同步,所以不用自己同步
 * 
 * @author csx
 *
 */
public class Main {
    public static void main(String[] args) {
        Table table = new Table(6);
        new EaterThread("eater 1", table).start();
        new EaterThread("eater 2", table).start();
        new EaterThread("eater 3", table).start();
        new ProducerThread("maker 1", table).start();
        new ProducerThread("maker 2", table).start();
        new ProducerThread("maker 3", table).start();
    }

}
  • Table.java (版本一:用数组表示桌子容量)
/**
 *此Table版本用数组,自己实现同步
 * @author csx
 *
 */
public class Table {
    private String[] mBuffer; //模拟table的容量
    private int mHead; //队列的头指针
    private int mTail; //队列的尾指针
    private int mCount; //队列中已有的蛋糕数量(table上现在有几个蛋糕)
    public Table(int count) {
        this.mBuffer = new String[count];
        this.mHead = 0;
        this.mTail = 0;
        this.mCount = 0;
    }
    public synchronized void put(String cake) throws Exception {
        while(mCount >= mBuffer.length) { //桌子已经放满蛋糕,需wait直到consumer取蛋糕
            wait();
        }
        mCount++;
        mBuffer[mTail] = cake;
        mTail = (mTail + 1) % mBuffer.length;
        System.out.println(Thread.currentThread().getName() +
                " put " + cake + "... count=" + mCount);
        notifyAll();
    }

    public synchronized void take() throws Exception {
        while(mCount <= 0) {//桌子已经没有蛋糕,需wait直到producer取蛋糕
            wait();
        }
        mCount--;
        String cake = mBuffer[mHead];
        System.out.println(Thread.currentThread().getName() + " eat "
                 + cake + "... count=" + mCount);
        mHead = (mHead + 1) % mBuffer.length;
        notifyAll();
    }

}
  • EaterThread.java
import java.util.Random;
public class EaterThread extends Thread {
    private Table mTable;
    Random mRandom;
    public EaterThread(String name, Table mTable) {
        super(name);
        this.mTable = mTable;
        mRandom = new Random();
    }
    @Override
    public void run() {
        while(true) {
            try {
                mTable.take();
                Thread.sleep(mRandom.nextInt(1000));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • ProducerThread.java
import java.util.Random;

public class ProducerThread extends Thread {

    private Table mTable;
    Random mRandom;
    private static int mCakeId = 0;
    public ProducerThread(String name, Table mTable) {
        super(name);
        this.mTable = mTable;
        mRandom = new Random();
    }

    @Override
    public void run() {
        while(true) {
            try {
                Thread.sleep(mRandom.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String cake = "No." + nextCakeId() + " maked by " + getName();
            try {
                mTable.put(cake);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static synchronized int nextCakeId() {
        return mCakeId++;
    }
}

结果图

这里写图片描述

Table的另外两种实现方式

Table.java (版本二:用LinkedList表示桌子容量,需要synchronized,其它类不用改变)
import java.util.LinkedList;
/**

 *  LinkedList容器自己实现同步

 * @author csx
 *
 */
public class Table {

    int mTotal; //桌子的容量大小
    private int mCount; //桌子上已经有的蛋糕数量
    LinkedList<String> mCakes; //模拟桌子存放蛋糕
    public Table(int count) {
        this.mCount = 0;
        this.mTotal = count;
        mCakes = new LinkedList<>();
    }

    public synchronized void put(String cake) throws Exception {
        while(mCount >= mTotal) { //桌子已放满蛋糕,需wait直到consumer取走至少一个蛋糕
            wait();
        }
        mCount++;
        mCakes.add(cake);
        System.out.println(Thread.currentThread().getName() + 
                " put " + cake + "... count=" + mCount);
        notifyAll();

    }

    public synchronized void take() throws Exception {
        while(mCount <= 0) {//桌子已经没有蛋糕,需wait直到producer生产至少一个蛋糕
            wait();
        }
        mCount--;
        String cake = mCakes.remove();
        System.out.println(Thread.currentThread().getName() + " eat " + cake + "... count=" + mCount);
        notifyAll();
    }

}
  • 结果图

这里写图片描述

Table.java (版本三:用ArrayBlockingQueue表示桌子容量,不需要synchronized,其它类不用改变,注意:take()和put()的调用者不能加synchronized,加了会死锁!!!)
public class Table {
    ArrayBlockingQueue<String> mArrayBlockingQueue; //模拟桌子存放蛋糕
    public Table(int count) {
        mArrayBlockingQueue = new ArrayBlockingQueue<>(count);
    }

    //take和put不能加synchronized,加了会死锁,因为ArrayBlockingQueue内部有加锁
    public void put(String cake) throws Exception { 
        System.out.println(Thread.currentThread().getName() + " put " + cake 
            + "... count=" + mArrayBlockingQueue.size());
        mArrayBlockingQueue.put(cake);
    }

    //take和put不能加synchronized,加了会死锁,因为ArrayBlockingQueue内部有加锁
    public void take() throws Exception {

        String cake = mArrayBlockingQueue.take();
        System.out.println(Thread.currentThread().getName() + " eat " 
                + cake + "... count=" + mArrayBlockingQueue.size());
    }

}
  • 结果图
    这里写图片描述

更高效的生产者和消费者模式

  • 用ReentrantLock中的Condition.因为生产者线程和消费者线程使用不同的Condition,所以唤醒线程时:对于消费者线程,只需唤醒所有的生产者线程即可;对于生产者线程,只需唤醒所有的消费者线程即可。

Table.java代码:

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

public class Table {

    int mTotal; //桌子的容量大小
    private int mCount; //桌子上已经有的蛋糕数量
    LinkedList<String> mCakes; //模拟桌子存放蛋糕
    private Lock mLock = new ReentrantLock();
    private Condition mProCondition = mLock.newCondition();
    private Condition mConCondition = mLock.newCondition();
    public Table(int count) {
        this.mCount = 0;
        this.mTotal = count;
        mCakes = new LinkedList<>();
    }

    public /*synchronized*/ void put(String cake) throws Exception {
        try {
            mLock.lock();
            while(mCount >= mTotal) { //桌子已放满蛋糕,需wait直到consumer取走至少一个蛋糕
//            wait();
                mProCondition.await();
            }
            mCount++;
            mCakes.add(cake);
            System.out.println(Thread.currentThread().getName() + 
                    " put " + cake + "... count=" + mCount);
//        notifyAll();
            //由于只是唤醒消费者线程,所以可以写成mConCondition.signal();

            mConCondition.signalAll();

        } finally {
            mLock.unlock();
        }

    }

    public /*synchronized*/ void take() throws Exception  {
        try {
            mLock.lock();
            while(mCount <= 0) {//桌子已经没有蛋糕,需wait直到producer生产至少一个蛋糕
//            wait();
                mConCondition.await();
            }
            mCount--;
            String cake = mCakes.remove();
            System.out.println(Thread.currentThread().getName() + " eat " + cake + "... count=" + mCount);
//        notifyAll();
            //由于只是唤醒生产者线程,所以可以写成mProCondition.signal();
            mProCondition.signalAll();
        } finally {
            mLock.unlock();
        }
    }

}

Main.java

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Main {

    static int p1 = 1; //生产者线程1计数用
    static int p2 = 1;//生产者线程2计数用
    static Random sRandom = new Random();
    public static void main(String[] args) {
        final Table table = new Table(4);
        //消费者
        new Thread(()->{
            while(true) {
                try {
                    table.take();
                    doSleep();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"consumer1").start();
        new Thread(()->{
            while(true) {
                try {
                    table.take();
                    doSleep();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"consumer2").start();
        //生产者
        new Thread(()->{
            while(true) {
                try {
                    table.put("No." + (p1++)
                            + " make by " + Thread.currentThread().getName());
                    doSleep();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"producer1").start();
        new Thread(()->{
            while(true) {
                try {
                    table.put("No." + (p2++)
                            + " make by " + Thread.currentThread().getName());
                    doSleep();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"producer2").start();
    }

    public static void doSleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(sRandom.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

结果图:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值