我粘贴了一些关于Java并发的代码:
public class ValueLatch <T> {
@GuardedBy("this") private T value = null;
private final CountDownLatch done = new CountDownLatch(1);
public boolean isSet() {
return (done.getCount() == 0);
}
public synchronized void setValue(T newValue) {
if (!isSet()) {
value = newValue;
done.countDown();
}
}
public T getValue() throws InterruptedException {
done.await();
synchronized (this) {
return value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么return value;需要同步???
返回语句不是原子的吗?
我正在阅读有关Java Volatile关键字的文章,遇到了一些问题。点击这里
public class MyClass {
private int years;
private int months
private volatile int days;
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}
Run Code Online (Sandbox Code Playgroud)
udpate()方法写入三个变量,其中只有几天是可变的。
完全易失的可见性保证意味着,当将值写入天时,线程可见的所有变量也将写入主存储器。这意味着,当将值写入天时,年和月的值也将写入主存储器。
那么,“线程可见的所有变量”是什么意思?这是否意味着线程堆栈中的所有变量?“线程可见”是什么意思?我如何知道该线程可以看到几个月和几年?