弱一致性指的是当list返回iterator,其他线程对list修改对iterator不可见
private static volatile CopyOnWriteArrayList<String> arrayList = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws InterruptedException {
arrayList.add("BOB");
arrayList.add("AOB");
arrayList.add("COB");
arrayList.add("DOB");
Thread thread = new Thread(() -> {
arrayList.add("hi bob");
arrayList.remove(2);
});
//获取迭代器
Iterator<String> it = arrayList.iterator();
thread.start();
// 等待子线程完成
//thread.join();
//迭代
while (it.hasNext()){
System.out.println(it.next());
}
System.out.println("=========================");
//获取修改好的迭代器
it = arrayList.iterator();
//再次迭代
while (it.hasNext()){
System.out.println(it.next());
}
}
output:
BOB
AOB
COB
DOB
========================
BOB
AOB
DOB
hi bob