Java 线程安全计数器未按预期工作

Java thread safe counter does not work as expected

我使用 AtomicInteger 实现了以下计数器 class。我从 this 文章中复制并粘贴了这个 class:

public class Counter {
  private final AtomicInteger counter = new AtomicInteger(0);

  public int get() {
      return counter.get();
  }

  public void increment() {
      while (true) {
          int existingValue = get();
          int newValue = existingValue + 1;
          if (counter.compareAndSet(existingValue, newValue)) {
              return;
          }
      }
  }
}

我写了下面的测试来确保它真的是一个线程安全的计数器:

@Test
public void counterWorksAsExpected() {
    IntStream.range(0, 100).forEach(j -> {
        int threads = 100;
        Counter counter = new Counter();

        ExecutorService executorService = Executors.newCachedThreadPool();
        IntStream.range(0, threads).forEach(i -> {
            executorService.execute(counter::increment);
        });
        executorService.shutdown();
        assertEquals(threads, counter.get());
    });
}

然而,在某个迭代中,assertEquals 失败了。

我想知道我的 Counter class 是否不是线程安全的。

您关闭了执行程序,但您没有等待提交的任务完成才断言。在检查结果之前添加对 awaitTermination() 的调用。