import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BlockedQueue<T> {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final int length = 100000;
Queue<T> queue = new LinkedList<T>();
void enq(T x) {
lock.lock();
try {
while(length == queue.size()) {
notFull.await();
}
System.out.println(System.currentTimeMillis() + "-入栈: " + x);
queue.add(x);
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void deq() {
lock.lock();
try {
while(queue.isEmpty()) {
notEmpty.await();
}
System.out.println(System.currentTimeMillis() + "-出栈: " + queue.remove());
notFull.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
BlockedQueue<Object> queue = new BlockedQueue<>();
new Timer("定时栈信息统计").schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时栈信息统计: " + queue.queue.size());
}
}, 1, 10000);
new Timer("定时入栈").schedule(new TimerTask() {
@Override
public void run() {
queue.enq(new Object());
}
}, 2, 100);
new Timer("定时出栈").schedule(new TimerTask() {
@Override
public void run() {
queue.deq();
}
}, 2, 1000);
}
}
Java实现阻塞队列
猜你喜欢
转载自blog.csdn.net/m0_37732829/article/details/111905453
今日推荐
周排行