java 多线程异步处理List拿到返回结果

public static void test10() throws ExecutionException, InterruptedException {
    List userList=new ArrayList<>();
    for(int i=0;i<1000;i++){
        TestUser testUser=new TestUser();
        testUser.setUsername("a"+i);
        testUser.setAge(1);
        userList.add(testUser);
    }
    List futureList=new ArrayList<>();
    for(TestUser testUser:userList){
        Future future=ThreadUtil.execAsync(new Callable (){
            @Override
            public TestUser call() throws Exception {
                Thread.sleep(1000);
                testUser.setAge(testUser.getAge()+1);
                return testUser;
            }
        });
        futureList.add(future);
    }
    List testUserList=new ArrayList<>();
    for(Future future:futureList){
        TestUser testUser=future.get();
        testUserList.add(testUser);
    }
    for(TestUser testUser:testUserList){
        System.out.println(testUser.toString());
    }
}

@Data
public class TestUser {
    private String username;
    private Integer age;
}

你可能感兴趣的:(java,list,蓝桥杯)