gpt4 book ai didi

java - 我会在这里同步什么?

转载 作者:行者123 更新时间:2023-11-29 04:57:25 25 4
gpt4 key购买 nike

首先是代码片段...

final public class ExampleClass {

final public class OperationQueue {

final private ConcurrentLinkedQueue<Operation> queue = new ConcurrentLinkedQueue<>();

public Operation newOp(Command command) {
Operation op = new Operation(command);
queue.add(op);
return op;
}

private boolean isEmpty() {
return queue.isEmpty();
}

private Operation remove() {
return queue.remove();
}

}
final public OperationQueue opQueue = new OperationQueue();

public void doSomething() {

synchronized (opQueue.queue) { // or synchronized(opQueue) ?
while (!opQueue.isEmpty()) {
process(opQueue.remove());
}
}
}

}

我的问题...

我需要同步什么? opQueue.queue?还是 opQueue?还是没关系?

实际上 opQueue.queue 甚至只能通过它位于 内部/嵌套类 中的怪癖来访问。

最佳答案

poll() 可能更好在你的情况下

public void doSomething() 
{
Operation op;
while( null != (op=queue.poll()) )
process( op );
}

关于java - 我会在这里同步什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33248564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com