多线添加锁仍然锁不住,输出结果变少

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
posted @ 2022-08-16 22:07  台风词典  阅读(42)  评论(0)    收藏  举报