我正在尝试创建一个线程安全计数器,但我不确定如何进行线程安全比较。 threadCount.get() 后跟 '==' 运算符线程安全吗?
public class ThreadSafeCounter {
private final AtomicInteger threadCount = new AtomicInteger(0);
//thread safe
public void increment() {
threadCount.getAndIncrement();
}
//thread safe
public void decrement() {
threadCount.getAndDecrement();
}
// is it safe ?
public boolean compareWith(int integer){
return threadCount.get() == integer;
}
}
最佳答案
在询问线程安全时,您需要问自己的问题是:“线程安全”是什么意思?
事实上,您真正需要解决的问题是调用它的代码是否安全。
您可以使用线程安全的数据结构执行某些操作,这些数据结构单独是线程安全的,但组合在一起时则不是线程安全的。
直接使用AtomicInteger
:
anAtomicInteger.incrementAndGet();
if (anAtomicInteger.get() < 5) {
// ...
}
这里的两个操作 - 递增和获取 - 都是线程安全的;但是 - 根据线程安全的 one 定义 - 它们放在一起时并不安全,因为有可能其他线程已经潜入并在其间增加了 anAtomicInteger
两个电话。
解决这个问题的方法是使用 incrementAndGet()
的返回值:
if (anAtomicInteger.incrementAndGet() < 5) {
// ...
}
保证以原子方式发生,因此不存在线程干扰。
您问题的答案以及解决方案取决于您想要解决的问题。
关于java - 线程安全比较方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60184690/