Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 线程安全比较方法_Java_Multithreading - Fatal编程技术网

Java 线程安全比较方法

Java 线程安全比较方法,java,multithreading,Java,Multithreading,我正在尝试创建一个线程安全计数器,但我不确定如何进行线程安全比较。 threadCount.get()后跟“==”运算符是否是线程安全的 public class ThreadSafeCounter { private final AtomicInteger threadCount = new AtomicInteger(0); //thread safe public void increment() { threadCount.getAndIncr

我正在尝试创建一个线程安全计数器,但我不确定如何进行线程安全比较。 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;
    }

}

在询问线程安全性时,您需要问自己的问题是:我所说的“线程安全”是什么意思

事实上,您真正需要解决的问题是调用它的代码是否安全

您可以使用线程安全的数据结构来做一些事情,这些数据结构单独是线程安全的,但组合在一起时不是线程安全的

直接使用原子整数:

anAtomicInteger.incrementAndGet();
if (anAtomicInteger.get() < 5) {
  // ...
}
这是保证发生原子,所以没有线程干扰那里


您的问题的答案和解决方案取决于您试图解决的问题。

它是线程安全的。但由于种族条件的原因,它不能保证比较是正确的。如果我们像这样重写代码,就会更容易看到它

    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;
    }


您打算如何使用
方法进行比较?无法保证其结果值在调用代码对其执行操作时是最新的。事实上,我认为根本没有办法以线程安全的方式使用此方法。您的权利,我将按照Andy Turner的建议使用
incrementAndGet()和decrementAndGet()
    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;
    }