我如何使用ArrayBlockingQueue與Spring Boot?我對佇列進行了如下配置 -
public class MessageQueueConfig {
public ArrayBlockingQueue arrayBlockingQueue() {
ArrayBlockingQueue<Message> arrayBlockingQueue = new ArrayBlockingQueue<> (50000)。
return arrayBlockingQueue。
}
在api呼叫中,我正在向佇列提供資料
private MessageQueueConfig queueConfig;
...
queueConfig.arrayBlockingQueue().offer(message, 5, TimeUnit.SECONDS)
為了poll佇列中的訊息,我需要使用執行緒嗎?或者我怎樣才能poll佇列中的訊息?可以直接使用@Autowired為消費者中的佇列和poll消費者中的訊息
uj5u.com熱心網友回復:
為了輪詢佇列中的訊息,我需要使用執行緒嗎?
根據檔案,BlockingQueue的實作是執行緒安全的。如果需要的話,你可以使用執行緒。
可以直接在消費者的佇列中使用 @Autowired 并在消費者中輪詢訊息
在消費者中這樣做:
@Autowired
private BlockingQueue< Message> arrayBlockingQueue;
//...
arrayBlockingQueue.poll(5, TimeUnit.SECONDS)
uj5u.com熱心網友回復:
直接的答案是No。
ArrayBlockingQueue是BlockingQueue介面的一個實作,它有鎖實作。
作為參考,我在下面發布了ArrayBlockingQueue的poll()和take()方法的源代碼實作。
public E poll() {
final ReentrantLock lock = this.lock。
lock.lock()。
try {
if (count == 0)
return null;
E x = extract()。
return x;
} finally {
lock.unlock()。
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock。
lock.lockInterruptibly()。
try {
try {
while (count == 0)
notEmpty.await()。
} catch (InterruptedException ie) {
notEmpty.signal(); //傳播到非中斷執行緒。
拋出 ie。
}
E x = extract()。
return x;
} finally {
lock.unlock()。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/325784.html
標籤:
上一篇:用Pythonic方法檢測串列在正值之后是否包含負值
下一篇:如何評估它?
