【发布时间】:2020-07-21 10:05:36
【问题描述】:
我注意到,如果我让一个线程填充一个集合,在join 之后的线程末尾,我会看到该集合按预期填充。
关于 Java 内存模型,这是否总能保证发生?
如果线程将列表中对象的引用存储在 cpu 缓存中怎么办?
在这种情况下,加入后加入线程必须保证看到更改?
final ArrayList<Person> persons = new ArrayList();
Thread myThread = new MyThread(persons);
myThread.start();
myThread.join();
// persons ?
线程
public class MyThread extends Thread {
ArrayList<Person> persons;
public MyThread(ArrayList<Person> persons){
this.persons = persons;
}
public void run(){
persons.add(new Person(...))
// add more
}
}
【问题讨论】:
-
join一个线程建立了一个happens-before。
标签: java multithreading collections thread-safety