首先是代码片段...
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/