如果故障安全的迭代器创建一个单独的副本并在其上工作,那么它如何意识到对原始数据的任何更改呢?
输出结果如下:
public class concurrentHashMap {
public static void main(String[] args) throws InterruptedException {
MapCheck obj1 = new MapCheck();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
obj1.put();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
obj1.iterte();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
class MapCheck {
Map<Integer,String> map = new ConcurrentHashMap<>();
{
map.put(1, "pujan");
map.put(2, "manish");
map.put(3, "swati");
}
void iterte() throws InterruptedException {
for (int key : map.keySet()) {
Thread.sleep(2000);
System.out.println(map.get(key));
}
}
void put() throws InterruptedException{
Thread.sleep(2000);
map.put(1, "pujan1");
map.put(2, "manish1");
map.put(3, "swati1");
}
}
输出结果如下:
pujan1
manish1
swati1