我有關於Java 7 ConcurrentLinkedQueue的以下問題。讓我們假設我有下面的類:使用ConcurrentLinkedQueue序列化訪問Collection <T>
public class Blah {
private ConcurrentLinkedQueue<String> queue;
public Blah() {
queue = new ConcurrentLinkedQueue<String>();
}
public void produce(String action, String task) throws InterruptedException {
synchronized(queue) {
while(queue.size() >= 8)
queue.wait();
queue.add(action + "#" + task);
queue.notifyAll();
}
}
public void consume() throws InterruptedException {
synchronized(queue) {
while(queue.size() <= 0)
queue.wait();
String element = queue.poll();
StringTokenizer strTok = new StringTokenizer(element, "#");
String action = strTok.nextToken();
String task = strTok.nextToken();
/**
* Operate on request
*/
queue.notifyAll();
}
}
}
的生產和消費的功能將併發線程,以便生成/從列表中刪除線程/調用。我實現了之前的函數consume()和produce(),以便序列化隊列中元素的添加/刪除。是上面的要求,還是ConcurrentLinkedQueue處理?我在問,因爲我不想降低我的代碼的性能。
謝謝 尼克
爲什麼你在地球上同步? –
@Boris因爲我希望自動執行關鍵部分內的所有操作。 –
這是'ConcurrentLinkedQueue'。如果使用正確,它保證原子性和可見性。你正在將一個非阻塞的'Queue'強制轉換爲['BlockingQueue'](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html)。 **別**。 –