![](/img/trans.png)
[英]Why do AtomicLong and AtomicLongFieldUpdater implement compareAndSet differently?
[英]atomicLong is it possible to do compareAndSet if atomic long larger than certain number?
我希望將AtomicLong
的當前timestamp
與currentTimeMS
進行比較,以便我知道是否經過了一段時間,如果是,那么只有一個線程會輸入代碼塊,但是從我看到的compareAndSet
只能與一個特定值進行比較,不可能如果value大於或小於另一個值,則執行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
遇到相同的問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.