实现说明
除了类 HitCounter,文件里再无其他定义。
重复被限制在 for (int t = 0; t < threads; t++) 里——其余代码按顺序各跑一遍。
使用要点
- 每一步打印都带着自己的标签:
expected =、sum =、after sumThenReset =。
常见问题
运行「LongAdder 高竞争计数器」会打印什么?
运行文件本身,expected =、sum =、after sumThenReset = 这些前缀各对应一段演示逻辑。
核心语句
ExecutorService pool = Executors.newFixedThreadPool(threads);
for (int i = 0; i < perThread; i++) {
hits.increment(); // 各线程写各自的 cell,不竞争同一个 CAS 变量
}
int perThread = 25_000;
代码示例
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
public class HitCounter {
public static void main(String[] args) throws InterruptedException {
LongAdder hits = new LongAdder();
int threads = 4;
int perThread = 25_000;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch done = new CountDownLatch(threads);
for (int t = 0; t < threads; t++) {
pool.submit(() -> {
for (int i = 0; i < perThread; i++) {
hits.increment(); // 各线程写各自的 cell,不竞争同一个 CAS 变量
}
done.countDown();
});
}
done.await();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("expected = " + (threads * perThread));
System.out.println("sum = " + hits.sum()); // 收尾一次性汇总
hits.add(50); // 批量累加同样支持
System.out.println("after sumThenReset = " + hits.sumThenReset());
}
}