sp; }
// 从list中读数据
public static class ReadThread implements Runnable {
@Override
public void run() {
System.out.println("start read size: " + list.size() + " thread : " + Thread.currentThread().getName());
for (UUID uuid : list) {
System.out.println("Read uuid : " + uuid + " size : " + list.size() + "thread: " + Thread.currentThread().getName());
}
}
}
public static void main(String[] args) throws InterruptedException {
initThread(new AddThread(), 10);
initThread(new ReadThread(), 100);
}
private static void initThread(Runnable runnable, int maxNum) throws InterruptedException {
Thread[] ts = new Thread[maxNum];
for (int k = 0; k < maxNum; k++) {
ts[k] = new Thread(runnable);
}
for (int k = 0; k < maxNum; k++) {
ts[k].start();
}
}
}
下图运行结果中可以看出来, 同一个线程, 即使在读的过程中发生了size变化, 也不会抛出ConcurrentModificationException