我正在尝试创建一个线程安全计数器,但我不知道如何进行线程安全比较。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;
}
}发布于 2020-02-12 09:21:53
在询问线程安全时,您需要问自己的问题是:我所说的“线程安全”是什么意思?
实际上,您真正需要解决的问题是调用它的代码是否安全。
您可以使用单独的线程安全的数据结构来做一些事情,但是当合并在一起时,这些数据结构并不是线程安全的。
直接使用AtomicInteger:
anAtomicInteger.incrementAndGet();
if (anAtomicInteger.get() < 5) {
// ...
}这里的两个操作--增量操作和获取操作--都是线程安全的;但是--根据线程安全的一个定义--它们在一起时不安全,因为有可能其他线程在两个调用之间潜入并增加了anAtomicInteger。
解决方案之一是使用incrementAndGet()的返回值。
if (anAtomicInteger.incrementAndGet() < 5) {
// ...
}这是保证发生原子,所以没有线程干扰在那里。
你的问题的答案和解决办法取决于你想要解决的问题。
发布于 2020-02-12 09:21:57
这是线安全。但这并不保证比较是正确的,因为种族条件。如果我们像这样重写代码,就会更容易看到它。
public boolean compareWith(int integer) {
int n = threadCount.get();
// so here, at this point, other thread(s), one, two, ten of them
// can call increment() or decrement()
// and so the number n which is used in the following comparsion
// is no longer the number actually stored in threadCount
return n == integer;
}https://stackoverflow.com/questions/60184690
复制相似问题