【发布时间】:2014-04-24 00:08:17
【问题描述】:
我希望将AtomicLong 中的当前timestamp 与currentTimeMS 进行比较,以便我知道是否已经过了一段时间,如果是,那么只有一个线程会输入一段代码,但从我看到的@987654324 @ 仅与特定值进行比较,如果值大于或小于另一个值,则无法执行 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
}
【问题讨论】:
-
看起来你做错事了,你想要的就是预定的动作。
-
使用调度器意味着我的代码中有更复杂的对象,我的测试会变得更加困难等等,在这里我只是做一个简单的时间比较,我发现比使用调度器更简单的设计,此外,如果我例如有一个缓存,那么如果没有命中就不需要预定的失效,但是如果我确实有命中我想检查最后一次失效是什么时候,这样使用这个“如果”我可以知道我是否有是否请求缓存
-
我不同意“更复杂”的东西——尤其是测试。相反,鉴于调度器的任务都是接口,你可以全部模拟它们
标签: java multithreading scala