Java多线程之运行多个任务并处理所有结果

执行器框架给我们提供了一个方法,让我们可以发送给执行器一个任务列表,并等待任务列表中的所有任务执行完毕。然后它将返回一个与任务列表对应的Future列表。

package com.primer.demo.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class ThreadPool {

    private static ExecutorService executorService = new ThreadPoolExecutor(100, 500, 1, TimeUnit.SECONDS, new LinkedBlockingDeque());

    public static  List addTask(List> tasks) {
        List> futureList = null;
        List results = null;
        try {
            futureList = executorService.invokeAll(tasks);
            results = new ArrayList<>();
            for (Future future : futureList) {
                results.add(future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return results;
    }
}

创建多个任务并显示结果:

package com.primer.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;

import com.primer.demo.util.ThreadPool;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Rollback(false)
public class Demo2ServiceTest {

    @Test
    public void test(){
        List> callables = new ArrayList<>();
        for(int i=0;i<10;i++){
            callables.add(()-> Math.random()+"");
        }
        List res = ThreadPool.addTask(callables);
        System.out.println("**********************");
        for(String str : res){
            System.out.println(str);
        }
    }
}

完整代码请参考:https://github.com/465919283/demo

你可能感兴趣的:(基础编程)