简体   繁体   English

MultipleThreads和同步线程可见性

[英]MultipleThreads and synchronization Thread Visibility

Say I have a Thread T1. 假设我有一个Thread T1。 I create an object in that thread eg Dog and set some properties ( name , color ) etc. 我在该线程中创建一个对象,例如Dog并设置一些属性( namecolor )等。

I then thread another Thread T2 (from T1) and pass the Dog object to it. 然后我将另一个线程T2(来自T1)线程化并将Dog对象传递给它。 After this point, T1 doesn't change anything properties of the object and doesn't even want to read it, but holds onto the actual reference ( Dog d ). 在此之后,T1不会更改对象的任何属性,甚至不想读取它,而是保留实际引用( Dog d )。

Question: 题:

  1. Assuming T2 doesn't change anything in Dog , is Dog Thread safe (from visibility stand-point. Will T2 always see the same name and color as set by T1)? 假设T2不会改变Dog任何内容,那么Dog Thread是安全的(从可见性的角度来看.T2是否总能看到与T1设置的相同的名称和颜色)?

Every actions in a thread can see whatever happened before that thread was started. 线程中的每个操作都可以看到该线程启动之前发生的任何事情。 In your example, T2 is guaranteed to see all changes made by T1 before t2.start() was called. 在您的示例中,T2保证在t2.start()之前看到T1所做的所有更改。

That does not make Dog thread safe but your use of that class is thread safe. 这不会使Dog线程安全,但您对该类的使用是线程安全的。

Note however that any subsequent changes made by either T1 or T2 after that point are not guaranteed to be visible from the other thread. 但请注意,在该点之后由T1或T2进行的任何后续更改都不能保证在其他线程中可见。


Reference: JLS #17.4.5 : 参考: JLS#17.4.5

A call to start() on a thread happens-before any actions in the started thread. 在启动线程中的任何操作之前,对线程的start()调用发生。

Dog is thread safe only if the values are just instance variables and volatile. 只有当值只是实例变量和volatile时, Dog才是线​​程安全的。

If they are not volatile there is a chance that T2 could read stale data. 如果它们不易变,那么T2有可能读取陈旧数据。

As long as: 只要:

  • your implementation guarantees being free of race conditions when accessing properties of your Dog d object by multiple threads simultaneously 您的实现保证在同时通过多个线程访问Dog d对象的属性时没有竞争条件

or 要么

  • Dog d 's properties' access is protected from race conditions Dog d的财产访问受到竞争条件的保护

... you can consider it to be thread safe. ...你可以认为它是线程安全的。

I would say that right now it is not possible to say whether your solution is thread safe or not. 我想说现在不可能说你的解决方案是否是线程安全的。 Because nothing is mentioned about data accessing principles or locks. 因为没有提到有关数据访问原则或锁的任何内容。

I suspect it is not thread safe! 我怀疑它不是线程安全的!

"is Dog Thread safe?" “狗线是否安全?” If its not immutable then I'd say no. 如果它不是一成不变的那么我就说不。

"from visibility stand-point. Will T2 always see the same name and color as set by T1?" “从可见性的角度来看.T2会不会看到与T1设定的名称和颜色相同的颜色?” Probably. 大概。 (watch out if things are not volatile or synchronized. (注意事情是否不稳定或同步。

Simple way to handle this is to synchronize on it. 处理此问题的简单方法是同步它。 that will make it thead-safe. 这将使它成为安全的。

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

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