并发编程复习(六):使用wait和notify模拟阻塞队列
来源:互联网 发布:销售票据打印软件 编辑:程序博客网 时间:2024/05/17 23:00
话不多说,代码如下
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<Object> 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
阅读全文
0 0
- 并发编程复习(六):使用wait和notify模拟阻塞队列
- 模拟阻塞队列-使用notify和wait
- 用wait和notify模拟阻塞队列
- java并发编程—— 六 进程协作:阻塞队列\wait() notify()\ Condition
- 并发编程复习(四):wait和notify解析
- 使用wait()和notify()模拟Queue(队列)
- 并发编程-wait,notify实现队列功能
- Java并发编程(六)阻塞队列
- Java并发编程(六)阻塞队列
- Java并发编程:wait()和notify()/notifyAll()
- 可阻塞队列 synchronized和wait/notify 线程堵塞锁
- wait和notify来设计阻塞式队列的流程
- 使用wait和notify模拟queue
- 阻塞队列(CountDownLatch代替notify+wait解决wait释放锁,notify不释放锁问题)
- java并发编程---wait、notify
- wait,notify,synchronized实现阻塞队列
- notify和notifyAll的区别及阻塞队列模拟实现
- Java并发编程系列之八:wait()、notify()和notifyAll()
- IOS开发之Views自定义布局
- 关于thinkphp里面公用模板的调用
- 【java基础】两个变量互换不使用第三方变量的方法
- 字符串的slice(),substr(),substring()
- [poj1155] TELE 树形DP 01背包
- 并发编程复习(六):使用wait和notify模拟阻塞队列
- 3379: [Usaco2004 Open]Turning in Homework 交作业
- 关于手机功能NFC(以华为V9为例)
- hdu 1698 Just a Hook
- 网格视图GridView的使用
- POJ 3155 Hard Life(最小割 最大密度子图)
- python3配置错误 ImportError: No module named 'gi._gi'
- bzoj1671 Knights of Ni 骑士 BFS
- 几首音乐