我希望将 AtomicLong
中的当前 timestamp
与 currentTimeMS
进行比较,以便我知道是否已经过去了一段时间,如果是,则只有一个单线程将进入一个代码块,但据我所知,compareAndSet
仅与特定值进行比较,如果值大于或小于另一个值,则不可能执行 compareAndSet
.这可能吗?
if (myAtomicLong.compareAndSet(larger than last atomic long value + 10 seconds,
System.currentTimeMillis() + 10 seconds)) {
// one thread enters here only as only one thread saw that current myAtomicLong
// was larger than last timestamp recorded + 10 seconds.
// and if yes immediately set the value to next 10 seconds.
// do some work
}
最佳答案
您应该为此使用 ScheduledExecutorService
。
原因很简单:System.currentTimeMillis()
并不像您想象的那么可靠……如果操作系统时间改变,它的值也会改变;而 ScheduledExecutorService
的实现使用 System.nanoTime()
,这是一个从 JVM 开始运行的自动收报机,它会一直增加。
注意 Timer
和 TimerTask
遇到同样的问题!
关于java - atomicLong 如果 atomic long 大于某个数字,是否可以进行 compareAndSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22477194/