public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {//用线程添加
new Thread(()->{ //lambda表达式
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {//输出前要加延时,不然主线程运行较快,其实添加线程还在运行,导致输出结果变少!!
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.size());
}
}
输出前要加延时,不然主线程运行太快,其实添加线程还在运行,导致输出结果变少!!
用sleep延时一下,不加延时输出结果会小于1000标签:输出,Thread,锁不住,list,多线,延时,new,添加 From: https://www.cnblogs.com/jazzybk/p/16593203.html