并发编程复习(六):使用wait和notify模拟阻塞队列
发布日期:2021-11-13 10:21:44 浏览次数:11 分类:技术文章

本文共 2448 字,大约阅读时间需要 8 分钟。

话不多说,代码如下

import java.util.LinkedList;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;/** * 使用wait和notify模拟阻塞队列...... */public class MyQueue {    private int minSize = 0;    private int maxSize;    public MyQueue(int size) {        this.maxSize = size;    }    private LinkedList list = new LinkedList<>();    private AtomicInteger count = new AtomicInteger();    private Object lock = new Object();    public void put(Object obj) {        synchronized (lock) {            while (count.intValue() == maxSize) {                try {                    lock.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            list.add(obj);            System.out.println("添加的元素为:"+obj);            count.incrementAndGet();            lock.notify();        }    }    public Object take() {        Object rel = null;        synchronized (lock) {            while (count.intValue() == minSize) {                try {                    lock.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            rel = list.removeFirst();            System.out.println("移除的元素为:"+rel);            count.decrementAndGet();            lock.notify();        }        return rel;    }    public Integer getSize() {        return list.size();    }    public static void main(String args[]) {        final MyQueue mq = new MyQueue(5);        mq.put("a");        mq.put("b");        mq.put("c");        mq.put("d");        mq.put("e");        System.out.println("队列中的对象个数为:"+mq.getSize());        Thread thread1 = new Thread(new Runnable() {            @Override            public void run() {                mq.put("f");                mq.put("g");            }        },"thread01:");        thread1.start();        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                 Object o = mq.take();                 System.out.println("取得的元素是:"+o);                 Object o1 = mq.take();                 System.out.println("取得的元素是:"+o1);            }        },"thread02:");        try {            TimeUnit.SECONDS.sleep(2);        } catch (InterruptedException e) {            e.printStackTrace();        }        t2.start();    }}
输出结果:

添加的元素为:a添加的元素为:b添加的元素为:c添加的元素为:d添加的元素为:e队列中的对象个数为:5移除的元素为:a添加的元素为:f取得的元素是:a移除的元素为:b取得的元素是:b添加的元素为:g

转载地址:https://blog.csdn.net/Lee_Ho_/article/details/78056459 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:并发编程复习(七):并发类容器ConcurrentHashMap&CopyOnWrite
下一篇:并发编程复习(五):CountDownLatch

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年03月26日 03时16分34秒