问题描述
我很惊讶Java的AtomicInteger和AtomicLong类没有模块化增量的方法(因此在达到限制后值会回绕到零)。
I was surprised that Java's AtomicInteger and AtomicLong classes don't have methods for modular increments (so that the value wraps around to zero after hitting a limit).
我想我必须遗漏一些明显的东西。最好的方法是什么?
I figure I've got to be missing something obvious. What's the best way to do this?
例如,我想在线程之间共享一个简单的int,我希望每个线程能够增加它,比方说, mod 10.
For example, I want to share a simple int between threads, and I want each thread to be able to increment it, say, mod 10.
我可以创建一个使用同步/锁定的类,但有更好,更简单的方法吗?
I can create a class which uses synchronization/locks, but is there a better, easier way?
推荐答案
在 addModular()$ c中添加
synchronized
修饰符或块有什么困难$ c>方法?
What's difficult about adding a synchronized
modifier or block to your addModular()
method?
Atomic
类没有此功能的原因是它们是基于当前CPU提供的,无法实现模块化算法那些没有诉诸锁定或其他更复杂和潜在效率低下的算法的人,比如亚特建议的算法。
The reason why the Atomic
classes don't have this functionality is that they're based on specific atomic hardware instructions offered by current CPUs, and modular arithmetic cannot be implemented by those without resorting to locking or other more complex and potentially inefficient algorithms like the one suggested by matt.
这篇关于使用Java的Atomic类进行模块化增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!