我无法在任何地方找到这个特定场景的答案。
如果我从两个线程同时调用 init()
,是否保证其中一个调用会看到 time
不再为空? time
是否也需要 volatile
?
它是不是像join()
一样是一个同步点?
private Long time;
synchronized void init() {
if (time != null) {
throw new IllegalStateException("Already initialised.");
}
this.time = System.currentTimeMillis();
}
最佳答案
当一个线程进入这个synchronized
方法时,它获得一个implicit
锁在实例上,它对实例的state
执行的更改实例对其他线程可见,等待进入同步方法。
when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
文档中的最后一行清楚地提到了它。状态是 volatile
还是 non-volatile
并不重要。
关于java - 对非 volatile 字段的同步访问线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210498/