簡體   English   中英

從另一個線程檢查時,ConcurrentLinkedQueue大小返回零

[英]ConcurrentLinkedQueue size returns zero when checked from a different thread

我有以下代碼:

Queue<Message> localMsgQueue;
//inside the constructor
localMsgQueue = new ConcurrentLinkedQueue<Message>();

public void AddMsg(Message m)
{
    localMsgQueue.offer(m);     
    System.out.println("^^"+localMsgQueue.size());

}
public void GetMsg() {
    System.out.println("+++" + localMsgQueue.size());       
}

在這里,在初始化隊列的主線程內調用AddMsg。 有時會從其他線程調用GetMsg。

我的問題是AddMsg內部的大小檢查返回隊列中元素的正確數量,而GetMsg始終返回零大小,盡管隊列中包含元素。

有人可以指出這里的問題嗎? 這是我第一次使用Java並發隊列,因此不確定發生了什么。

您可能正在構造兩個不同的ConcurrentLinkedQueue<Message>對象。

在您的類的構造函數中放置一個斷點,看看它被擊中了多少次。

// put a breakpoint here
localMsgQueue = new ConcurrentLinkedQueue<Message>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM