【发布时间】:2015-03-12 17:03:01
【问题描述】:
已经有一个question whether threads can simultaneously safely read/iterate LinkeList。似乎答案是肯定的,只要没有人从链表中对其进行结构更改(添加/删除)。
虽然一个答案是警告“未刷新的缓存”并建议了解“Java 内存模型”。所以我要求详细说明那些“邪恶”的缓存。我是一个新手,到目前为止我仍然天真地认为以下代码是可以的(至少从我的测试来看)
public static class workerThread implements Runnable {
LinkedList<Integer> ll_only_for_read;
PrintWriter writer;
public workerThread(LinkedList<Integer> ll,int id2) throws Exception {
ll_only_for_read = ll;
writer = new PrintWriter("file."+id2, "UTF-8");
}
@Override
public void run() {
for(Integer i : ll_only_for_read) writer.println(" ll:"+i);
writer.close();
}
}
public static void main(String args[]) throws Exception{
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i=0;i<1e3;i++) ll.add(i);
// do I need to call something special here? (in order to say:
// "hey LinkeList flush all your data from local cache
// you will be now a good boy and share those data among
// whole lot of interesting threads. Don't worry though they will only read
// you, no thread would dare to change you"
new Thread(new workerThread(ll,1)).start();
new Thread(new workerThread(ll,2)).start();
}
【问题讨论】:
标签: java multithreading synchronization