您的位置:首页 > 编程语言

并发编程复习(六):使用wait和notify模拟阻塞队列

2017-09-21 20:20 633 查看
话不多说,代码如下

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并发 java 编程