如何使用并发 类 在 java 中减少一个字段并自动增加另一个字段

How to decrement one field and increment another field atomically in java using concurrency classes

我有一个状态机 - 挂起和完成 - AtomicLong(线程)。我需要以原子方式递减 pending 和 increment completed

private final AtomicLong pending = new AtomicLong();
private final AtomicLong completed = new AtomicLong();

void markComplete() {
  this.pending.decrementAndGet();
  this.completed.incrementAndGet();
}

我可以通过使用块进行同步来使它成为原子。但这似乎打败了并发对象的使用。

synchronized void markComplete() {
  this.pending.decrementAndGet();
  this.completed.incrementAndGet();
}

我想知道是否有更好的方法来做到这一点?

谢谢你帮助我。

不要更新 currentPending,因为它是可推导的。保持固定并使用这个:

public long getCurrentPending() {
    return currentPending.get() - completed.get();
}

当你添加项目时,你总是可以增加 currentPending 而不会破坏任何东西。

并发对象仅对使单值线程安全有用。如果你想对多个值进行并发,你将不得不使用锁定(如同步)

如果 pendingcomplete 适合 int 范围(并且只要在调用 markComplete() 时 pending 大于零)你就可以做一些事情这些行:

private final AtomicLong pendingAndComplete = new AtomicLong();

void markComplete() {
  this.pendingAndComplete.addAndGet(1L<<32-1); // this is atomic
}
void markPending() {
  this.pendingAndComplete.incrementAndGet(); // this is atomic
}

void doSomething() {
  long current = this.pendingAndComplete.get(); // this fetches the current state atomically

  int currentCompleted = (int)(current >> 32);
  int currentPending = (int) current;
}