有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程有没有一种方法可以实现java中线程安全/原子的ifelse条件?

让我们举个例子:

 public class XYZ{
    private AtomicInteger var1;
    private int const_val;

    // these all attributes are initialized with a constructor, when an instance of the class is called.

    // my focus is on this method, to make this thread-safe
    public boolean isPossible(){
        if(var1 < const_val){
            var1.incrementAndGet();
            return true;
        }
        else{
            return false;
        }
    }
}

如果我不能使用锁机制(在java中),如何使这个(整个“if-else”代码段)成为线程安全/原子的

我读了一些关于原子整数的东西,读了一些关于原子布尔的东西,我能用它们来保证这个片段的线程安全吗


共 (2) 个答案

  1. # 1 楼答案

    您可以无条件递增,而不是在写入时强制执行最大值,并在读取时强制执行最大值,如下所示:

    public boolean increment(){
        return var1.getAndIncrement() < const_val;
    }
    
    public int getVar1() {
        return Math.min(const_val, var1.get());
    }
    

    假设你对这个变量所做的就是增加它。此解决方案的一个问题是,它最终可能导致溢出。如果这是一个可能的问题,您可以切换到AtomicLong

  2. # 2 楼答案

    像这样的东西应该能奏效

    public boolean isPossible(){
        for(;;){
            int current = var1.get();
            if(current>=max){
                return false;
            }
            
            if(var1.compareAndSet(current, current+1)){
                return true;
            }
        }
        
    }