我到处都读到过,如果一个字段同时由不同的线程使用,则需要某种同步,而如果仅由一个线程使用,则不需要。但是,如果不同线程同时使用它却又怎么办呢?
让我们采用这样的代码:
Thing thing = new Thing();
Thread t1 = new Thread(new MyRunnable(thing));
Thread t2 = new Thread(new MyRunnable(thing));
t1.start();
t1.join();//Wait for t1 to finish
t2.start();
MyRunnable是:
class MyRunnable implements Runnable {
//skipped constructor and field "private final Thing thing"
public void run() {
thing.someUpdate();
}
}
安全吗? t2可以看到t1所做的所有更新吗?
最佳答案
在这种情况下,更改是可见的,因为Thread.join
和Thread.start
在两个线程中的 Action 之间建立关系之前发生。参见Memory Consistency Errors:
如果未按顺序使用这些方法,则更改可能不可见。线程不需要同时运行就可以引起问题,因为可以将值缓存在线程中,也可以进行一些优化等。
关于java - 在不同线程中使用对象但不是同时使用一个对象是否安全?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36273089/