简体   繁体   English

同步块中的操作是否对其他线程可见?

[英]Are actions in a synchronized block visible to other threads?

I have read this Related Question and the answer help a lot, but there is still a question.我已经阅读了这个相关问题,答案很有帮助,但仍然有一个问题。

I heard that changes of shared fields in a synchronized block is guaranteed visible to other threads.我听说同步块中共享字段的更改保证对其他线程可见。

For codes like this:对于这样的代码:

Thread1:线程 1:

synchronized(lock) {
   obj.field1 = value1;
}

Thread2:线程2:

synchronized(lock) {
   System.out.println(obj.field1);
}

Assuming thread1 precedes thread2, it is said that according to the Java Specification, it may go like this:假设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 stands for happens-before in Java Specification, and it guaranteed the visibility. hb 在 Java 规范中代表happens-before,它保证了可见性。

And because " If hb(x, y) and hb(y, z), then hb(x, z) ", we get:因为“如果 hb(x, y) 和 hb(y, z), then hb(x, z)”,我们得到:

hb(write to obj.field1 in threadOne, read from obj.field1 in threadTwo) 

My question is on the first line:我的问题在第一行:

hb(write to obj.field1 in threadOne, unlock in threadOne) 

In Java Specification, I only found:在 Java 规范中,我只发现:

An unlock action on monitor m synchronizes-with all subsequent lock actions on m (where "subsequent" is defined according to the synchronization order).监视器 m 上的解锁操作与 m 上的所有后续锁定操作同步(其中“后续”根据同步顺序定义)。

That indicates the unlock action happens-before subsequent lock actions.这表明解锁动作发生在随后的锁定动作之前。 But I cannot find words like:但我找不到这样的词:

An action in synchronized block happens-before the unlock action.同步块中的动作发生在解锁动作之前。

So is it correct?那么它是正确的吗? And where can I find it ?我在哪里可以找到它?

All actions of the same thread are ordered by the happens-before relation.同一线程的所有操作都按发生在之前的关系排序。

JLS 17.4.5: 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).如果 x 和 y 是同一线程的操作,并且 x 在程序顺序中排在 y 之前,则 hb(x, y)。

Also note, that happens-before is transitive, thus if the write within the synchronized block happens before unlock, and unlock happens before a lock on another thread, then the write happens before any action in the synchronized block in the other thread.还要注意,happens-before 是可传递的,因此如果同步块中的写入发生在解锁之前,并且解锁发生在另一个线程上的锁定之前,那么写入发生在另一个线程中同步块中的任何操作之前。

The best explanation here is that unlock action has a happens-before edge with the last action in the thread.这里最好的解释是解锁动作有一个发生在线程中最后一个动作之前的边缘。 It's called program order.这叫做程序顺序。 It's described in the documentation它在文档中描述

Among all the inter-thread actions performed by each thread t, the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM