ConcurrentHashMap javadoc指出
它们不会抛出 ConcurrentModificationException。但是,迭代器被设计为一次只能由一个线程使用。
但是下面的代码输出结果就像两个线程可以同时在迭代器上运行。
ConcurrentHashMap<String,Boolean> ref = new ConcurrentHashMap<String,Boolean>();
new Thread("Insertion"){
public void run(){
for(int i = 0; i < 100; i++){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
ref.put(""+i,Boolean.TRUE);
}
}
}.start();
new Thread("Iterator_1"){
public void run(){
Iterator itr = ref.keySet().iterator();
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
}
while(itr.hasNext()){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread()+"" + itr.next());
}
}
}.start();
new Thread("Iterator_2"){
public void run(){
Iterator itr = ref.keySet().iterator();
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
}
while(itr.hasNext()){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread()+"" + itr.next());
}
}
}.start();
输出显示两个迭代器一起工作。请帮助理解这个 javadoc 语句。
Thread[Iterator_1,5,main]67
Thread[Iterator_2,5,main]81
Thread[Iterator_1,5,main]2
Thread[Iterator_2,5,main]59
Thread[Iterator_1,5,main]81
Thread[Iterator_2,5,main]40