我有以下关于 Java 7 ConcurrentLinkedQueue 的问题。让我们假设我有以下课程:
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 负责?我问是因为我不想降低代码的性能。
谢谢你,尼克