-->

Java使用多线程池给List赋值导致List存在空的处理

错误示例:

    public List<String> test() throws NuMaxCloudCommonException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Future<?> future = executorService.submit(() -> {
                list.add("a");
            });
        }
        return list;
    }

返回结果:[a],[a,a],[a,a,a]不一定,就是因为线程池使用了非线程安全的列表,所以会出现元素空的情况

正确示例:

public List<String> test() throws NuMaxCloudCommonException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 3; i++) {
            Future<?> future = executorService.submit(() -> {
                list.add("a");
            });
        }
        return list;
    }

结果一直是:

[
  "a",
  "a",
  "a"
]
posted @ 2024-08-03 19:17  ꧁ʚ星月天空ɞ꧂  阅读(130)  评论(0)    收藏  举报