微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法在java中实现线程安全/原子的if-else条件?

如何解决有没有办法在java中实现线程安全/原子的if-else条件?

举个例子:

 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”片段)线程安全/原子化?

我在 AtomicIntegers 行上阅读了一些内容,并使用 AtomicBooleans 阅读了一些内容,我可以使用这些内容使此代码段成为线程安全的吗?

解决方法

这样的事情应该可以解决问题。

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

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

public boolean increment(){
    return var1.getAndIncrement() < const_val;
}

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。