实现阻塞队列

阻塞队列不用java自身封装好的,也除了conditionwait方式,还有什么方式吗?(代码附condition和wait方式)
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//我们自己来实现个阻塞队列,主要实现方法是size(),take(),put()即可
public class MyBlockedQueue<E> {
private ReentrantLock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition();
//下面是队列的属性
private Object[] items;
public volatile int count =0;
MyBlockedQueue(int size){
items = new Object[size];
}
public void put(Object obj) throws InterruptedException{
lock.lock();
try{
while(count == items.length){
System.out.println("队列已满,无法继续放入元素");
notFull.await();
}
items[count++] = obj;
System.out.println("放入元素");
System.out.println("此时队列的元素个数为"+size());
notEmpty.signal();
}finally {
lock.unlock();
}
}
public Object take() throws InterruptedException{
Object obj ;
lock.lock();
try{
if(count == 0){
System.out.println("队列为空,无元素可取");
notEmpty.await();
}
obj = items[--count];
System.out.println("取出元素");
System.out.println("此时队列的元素个数为"+size());
notFull.signal();
return obj;
}finally {
lock.unlock();
}
}
public int size(){
return this.count;
}
public static void main(String[] args) throws InterruptedException {
MyBlockedQueue queue = new MyBlockedQueue<>(10);
Random r = new Random();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
while(true){
queue.take();
Thread.sleep(r.nextInt(900));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
while(true){
queue.put(1);
Thread.sleep(r.nextInt(1000));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
} }

#Java#
全部评论
https://juejin.im/entry/596343686fb9a06bbd6f888c
点赞 回复 分享
发布于 2019-08-07 14:08
blockingqueue?
点赞 回复 分享
发布于 2019-08-07 14:01
你这个排版咋回事儿...😂
点赞 回复 分享
发布于 2019-08-07 14:30

相关推荐

10-28 11:04
已编辑
美团_后端实习生(实习员工)
一个2人:我说几个点吧,你的实习经历写的让人觉得毫无含金量,你没有挖掘你需求里的 亮点, 让人觉得你不仅打杂还摆烂。然后你的简历太长了🤣你这个实习经历看完,估计没几个人愿意接着看下去, sdk, 索引这种东西单拎出来说太顶真了兄弟,好好优化下简历吧
点赞 评论 收藏
分享
1 9 评论
分享
牛客网
牛客企业服务