首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用volatile跳过方法执行

使用volatile跳过方法执行
EN

Stack Overflow用户
提问于 2020-06-19 22:33:25
回答 1查看 52关注 0票数 0

我从来不经常使用易失性。如果另一个线程正在执行它,是否可以使用它跳过方法的执行?我认为在下面的代码中,仍然可能有多个线程通过检查并执行该方法。难到不是么?

代码语言:javascript
复制
private static boolean volatile test = false;
...
    public void test() {
        if (test) {
            return;
        }
        test = true;
        try {
            System.out.println("test() started in Thread with ID " + Thread.currentThread().getId());
            Thread.sleep(10000);
            System.out.println("test() finished in Thread with ID " + Thread.currentThread().getId());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        test = false;
    }

用例:该方法可以定期运行,但同时也可以由用户手动触发。没有理由使用synchronized关键字连续运行两次。请告诉我用易失性是可行的。否则,我看不出有任何理由去理解它,除了求职面试:)其他不基于易失性的解决方案是受欢迎的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-19 23:18:04

您可以像这样使用volatile AtomicBoolean来满足您的需求。

代码语言:javascript
复制
// default false so that first-thread that test() can enter the logic block
// AtomicBoolean's value is inherently volatile, so no need to declare volatile here
private static final AtomicBoolean test = new AtomicBoolean(false);   


public void test() {
    if (test.compareAndSet(false, true)) {  // check if the test if previously false and if so update it to true
        try {
            System.out.println("test() started in Thread with ID " + Thread.currentThread().getId());
            Thread.sleep(10000);
            System.out.println("test() finished in Thread with ID " + Thread.currentThread().getId());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            test.set(false); // executing thread now re-sets the test value
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62472524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档