zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LinkedBlockingQueue 消费队列

2023-04-18 15:49:18 时间

take元素原理

 基本过程:

1.加锁(依旧是ReentrantLock),注意这里的锁和写入是不同的两把锁

2.判断队列是否为空,如果为空就一直等待

3.通过dequeue方法取得数据

3.取走元素后队列是否为空,如果不为空唤醒其他等待中的队列

 
offer(E e)

参数:此方法接受强制参数e,该参数是要插入队列中的元素。


返回:成功插入时此方法返回true,否则返回false。


-------------------------------------------------------------------

private ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
new CustomizableThreadFactory("BackTestingWebSocketPool-"));
---------------------------------------------- 线程
static LinkedBlockingQueue<CommWebSocketMsg> logQueue = new LinkedBlockingQueue();
----------------------------------- new 一个队列

public static void pushMsg(CommWebSocketMsg msg) {
if (!CommWebSocketMsg.MSG_TYPE_PUSH_BACK_TEST_LOG.equals(msg.getMsgType())) {
push2Socket(msg);
return;
}

if (!logQueue.offer(msg)) {
logger.error(String.format("加入队列 失败.{%s}", msg));
}
}
-------------------------------- offer(E e)

CommWebSocketMsg msg = logQueue.take();    取数据
------------------------------------take()