public class Demo1 {
public static void main(String[] args) throws InterruptedException {
List<String> list = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < 5; i++) {
int temp = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 5; j++) {
list.add(Thread.currentThread().getName() + " " + temp + " " + j);
}
}
});
thread.start();
}
System.out.println(list.size());
}
}
理论结果是25 但实际结果是随机的
原因是主线程执行的速度,可能主线程执行完 ,子线程数据还没有添加完,造成获取的集合大小不匹配
修改方案是让子线程join加入让子线程执行完后再输出集合大小
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
// List<String> list=new ArrayList<>();
List<String> list = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < 5; i++) {
int temp = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 5; j++) {
list.add(Thread.currentThread().getName() + " " + temp + " " + j);
}
}
});
thread.start();
thread.join();
}
//主线程执行完 子线程继续添加
System.out.println(list.size());
}
}