package com.zkk;
// 实时同步队列
// 队列大小为1,且push时,如果队列中有数据,则老数据会被新数据替代
public class RealtimeBlockingQueue<T>
{
// 队列长度为1,以保证pop时得到的都是实时数据
private T _data = null;
private boolean isQuit = false;
private final boolean _isEmpty()
{
return _data == null;
}
public int size()
{
return _data == null? 0: 1;
}
// 将图像压入队列,如果队列中已有图像,则用新图像替代老图像
public synchronized void put(T data) {
// 队列是否已空
boolean isQueueEmpty = _isEmpty();
if (!isQueueEmpty){
System.out.println("** Discard " + _data);
}
// 向队列中加入新图像
this._data = data;
// 如果此前队列已空,则有可能有任务正在等待新图像,唤醒这些任务
if (isQueueEmpty)
{
notifyAll();
}
}
public synchronized T clear() {
T data = _data;
_data = null;
return data;
}
public synchronized T quit() {
T data = _data;
_data = null;
isQuit = true;
return data;
}
// 将图像从队列中取出,如果队列已空,则等待
public synchronized T take() throws InterruptedException
{
/* while(_isEmpty() && !isQuit)
{
System.out.println("aa"+System.currentTimeMillis());
wait();
System.out.println("bb"+System.currentTimeMillis());
}
*/
if(_isEmpty() && !isQuit)
{
wait(1000);
}
T data = _data;
_data = null;
return data;
}
}
单个队列
最新推荐文章于 2022-12-14 17:14:19 发布