我从来不经常使用易失性。如果另一个线程正在执行它,是否可以使用它跳过方法的执行?我认为在下面的代码中,仍然可能有多个线程通过检查并执行该方法。难到不是么?
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关键字连续运行两次。请告诉我用易失性是可行的。否则,我看不出有任何理由去理解它,除了求职面试:)其他不基于易失性的解决方案是受欢迎的。
发布于 2020-06-19 23:18:04
您可以像这样使用volatile AtomicBoolean来满足您的需求。
// 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
}
}
}https://stackoverflow.com/questions/62472524
复制相似问题