java: 线程间通信经典模型“生产者-消费者”模型的实现

18 篇文章 0 订阅

安利一个网站:在线文档 jdk 1.6


一篇有参考价值的关于锁对象使用的博文:ReadLock和WriteLock(读写锁)


  • java 对于多线程的控制提供了很多操作对象,方法。比如synchronized关键字,还有Object#wait() & Object#notify() & Object#notifyAll();
  • 不过java还提供了一些其他的工具类,比如Lock & ReentrantLock & ReentrantReadWriteLock & Condition
    • 理论上,后面这套机制完全可以取代前面的那一套。
  • 基于Lock & ReentrantLock & ReentrantReadWriteLock & Condition这些工具,我实现了一个简单的“生产者-消费者”模型。

核心代码如下:

package com.cat.multi.compete;

import java.awt.image.LookupOp;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.*;

/**
 * Created by cat on 2018/1/21.
 * 实现模型:
 * <p>
 * 生产者一直生产,直到产品数量达到 N, 就停止生产。
 * <p>
 * 并且,当产品到达 N 的时候,生产者要通知消费者来消费。
 * 同时:
 * <p>
 * 消费者一直消费,直到产品数量为0,就停止消费。
 * <p>
 * 并且,当没有产品的时候,消费者要通知生产者继续生产;
 * <p>
 * 基于多线程的,可以有任意多个生产者,以及任意多个消费者,不限制两个群体的数量。
 * <p>
 * -------------------------------------
 */
public class Repertory<T> {

    private static final int MIN_MAX = 10;
    private static final int SLEEP = 100;
    private static final boolean DEBUG = false;
    private static final boolean Loggable = false;
    private static final boolean LIMIT = false;


    private final Condition putCondition;
    private final Condition takeCondition;

    private List<T> itemList;
    private int max;

    private ReentrantReadWriteLock.WriteLock writeLock;
    private ReentrantReadWriteLock.ReadLock readLock;

    public Repertory() {
        this(MIN_MAX);
    }

    public Repertory(int max) {
        // init collection
        if (max < MIN_MAX) {
            max = MIN_MAX;
        }
        this.max = max;
        if (LIMIT) {
            this.max = 1;
        }
        itemList = new LinkedList<>();
        // init rwLock
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        writeLock = rwLock.writeLock();
        readLock = rwLock.readLock();
        putCondition = writeLock.newCondition();
        takeCondition = writeLock.newCondition();
    }

    private boolean isEmpty() {
        return this.itemList.size() == 0;
    }

    private boolean isFull() {
        return this.itemList.size() == max;
    }

    private boolean needPut() {
        if (LIMIT) {
            return isEmpty();
        }
        return isEmpty() || itemList.size() <= max / 5;
    }

    private boolean needTake() {
        if (LIMIT) {
            return isFull();
        }
        return isFull() || itemList.size() > max * 4 / 5;
    }

    private void checkAccess() {
        if (needPut() && needTake()) {
            throw new RuntimeException("判断条件出错,必须修改程序...");
        }
    }

    /**
     * 该方法只应该被【生产者】线程调用,否则容易出现死锁
     *
     * @param obj 生产的对象
     * @throws InterruptedException 中断异常
     */
    public void put(T obj) throws InterruptedException {

        writeLock.lock();
        try {
            checkAccess();
            while (needTake()) {
                takeCondition.signalAll();
                putCondition.await(); // 满了,就等待,并通知消费者取货
            }
            if (DEBUG || LIMIT) {
                Thread.sleep(SLEEP);
            }
            itemList.add(obj);
            if (DEBUG || Loggable) {
                System.out.println(Thread.currentThread().getName() + "-put--" + obj);
            }
        } finally {
            writeLock.unlock();
        }
    }

    /**
     * 该方法只应该被【消费者】线程调用,否则容易出现死锁
     *
     * @throws InterruptedException 中断异常
     */
    public void take() throws InterruptedException {
        writeLock.lock();
        try {
            checkAccess();
            while (needPut()) {
                putCondition.signalAll(); // TODO:这里要注意,一定要先去唤醒对象,然后再让自己休息!,
                takeCondition.await(); // 否则,自己休息了,也就没有机会唤醒对方了...
            }
            if (DEBUG || LIMIT) {
                Thread.sleep(SLEEP);
            }
            T obj = itemList.remove(0);
            if (DEBUG || Loggable) {
                System.out.println(Thread.currentThread().getName() + "-take--" + obj);
            }
        } finally {
            writeLock.unlock();
        }
    }

    public void show() {
        readLock.lock();
        try {
            System.err.println("SHOW ### " + this.toString());
        } finally {
            readLock.unlock();
        }
    }

    @Override
    public String toString() {
        String msg = "";
        if (DEBUG || Loggable || itemList.size() < MIN_MAX) {
            msg = "Repertory{" +
                    "max=" + max +
                    " , length=" + itemList.size() +
                    " , itemList=" + itemList +
                    '}';
        } else {
            msg = "Repertory{" +
                    "max=" + max +
                    " , length=" + itemList.size() +
                    " , itemList=" + itemList.hashCode() +
                    '}';
        }
        return msg;
    }
}

在这里,我设计了一个弹性的提醒机制:当产品数量不多的时候,就取提醒生产者继续生产,当产品快要填满仓库的时候,提醒消费者去消费产品

主要是要注意LockCondition的使用。什么时候去唤醒对象,什么时候去锁住自己。

贴一下运行效果:

main....done
SHOW ### Repertory{max=800 , length=160 , itemList=-1860611849}
SHOW ### Repertory{max=800 , length=160 , itemList=-1298639763}
SHOW ### Repertory{max=800 , length=160 , itemList=2000215250}
SHOW ### Repertory{max=800 , length=641 , itemList=-1309744438}
SHOW ### Repertory{max=800 , length=540 , itemList=1941569576}
SHOW ### Repertory{max=800 , length=641 , itemList=-1381681245}
SHOW ### Repertory{max=800 , length=583 , itemList=-452614553}
SHOW ### Repertory{max=800 , length=584 , itemList=861488929}
SHOW ### Repertory{max=800 , length=403 , itemList=96019575}
SHOW ### Repertory{max=800 , length=630 , itemList=1046072484}
SHOW ### Repertory{max=800 , length=641 , itemList=-1165811446}
SHOW ### Repertory{max=800 , length=516 , itemList=1904956760}
SHOW ### Repertory{max=800 , length=641 , itemList=-1900689143}
SHOW ### Repertory{max=800 , length=641 , itemList=361414021}
SHOW ### Repertory{max=800 , length=160 , itemList=-556965428}
SHOW ### Repertory{max=800 , length=160 , itemList=-1430830115}
SHOW ### Repertory{max=800 , length=160 , itemList=-1057490965}
SHOW ### Repertory{max=800 , length=542 , itemList=-523711472}
SHOW ### Repertory{max=800 , length=160 , itemList=1731272543}
SHOW ### Repertory{max=800 , length=269 , itemList=-1022961313}
SHOW ### Repertory{max=800 , length=638 , itemList=1221651327}
SHOW ### Repertory{max=800 , length=641 , itemList=1042805193}
SHOW ### Repertory{max=800 , length=160 , itemList=-1602343791}
SHOW ### Repertory{max=800 , length=535 , itemList=-1074051187}
SHOW ### Repertory{max=800 , length=614 , itemList=130345902}
SHOW ### Repertory{max=800 , length=160 , itemList=1746308531}
SHOW ### Repertory{max=800 , length=160 , itemList=454520929}
SHOW ### Repertory{max=800 , length=641 , itemList=-1199120192}
SHOW ### Repertory{max=800 , length=160 , itemList=1381613569}
SHOW ### Repertory{max=800 , length=160 , itemList=-249456061}
SHOW ### Repertory{max=800 , length=353 , itemList=-503794141}

Process finished with exit code 130 (interrupted by signal 2: SIGINT)

log上面大致可以看到,设计的最大值是800,然后生产者和消费在间歇作业,只要满足等待条件,就唤醒对方,并自己休息。

完整源码:可以在彩蛋里面拿到。~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值