我读过这篇文章Related Question答案很有帮助,但仍然有一个问题。
我听说同步块(synchronized block)中共享字段的更改保证对其他线程可见。
对于这样的代码:
主题1:
synchronized(lock) {
obj.field1 = value1;
}
线程2:
synchronized(lock) {
System.out.println(obj.field1);
}
假设thread1先于thread2,据说根据Java规范,可能会这样:
hb(write to obj.field1 in threadOne, unlock in threadOne) AND
hb(unlock in threadOne, lock in threadTwo) AND
hb(lock in threadTwo, read from obj.field in threadTwo)
hb在Java规范中代表happens-before,它保证了可见性。
因为“如果 hb(x, y) 和 hb(y, z),则 hb(x, z) ”,我们得到:
hb(write to obj.field1 in threadOne, read from obj.field1 in threadTwo)
我的问题在第一行:
hb(write to obj.field1 in threadOne, unlock in threadOne)
在Java规范中,我只发现:
An unlock action on monitor m synchronizes-with all subsequent lock actions on m (where "subsequent" is defined according to the synchronization order).
这表示解锁操作发生在后续锁定操作之前。但我找不到这样的词:
An action in synchronized block happens-before the unlock action.
那么它正确吗?我在哪里可以找到它?
最佳答案
同一线程的所有操作均按发生前关系排序。
JLS 17.4.5:
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
另请注意,发生之前是传递性的,因此如果同步块(synchronized block)内的写入发生在解锁之前,并且解锁发生在另一个线程上的锁之前,则写入发生在另一个线程的同步块(synchronized block)中的任何操作之前.
关于java - 同步块(synchronized block)中的操作对其他线程可见吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60882316/