FutureTask获取多线程处理结果

package com.test.ThreadPoolExecutor;


import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureThreadCase {

    public static void main(String[] args){
        List prehandlerList = new ArrayList<>();
        FutureThreadCase futureThreadCase = new FutureThreadCase();
        for(int i = 1; i <= 10; i++){
            prehandlerList.add(i);
        }
        ExecutorService executor = Executors.newFixedThreadPool(3);
        List> futureList = new ArrayList<>();
        for(Integer handler: prehandlerList){
            FutureTask futureTask = new FutureTask<>(() -> futureThreadCase.deal(handler));
            executor.submit(futureTask);
            futureList.add(futureTask);
        }
        executor.shutdown();

        List finalResult = new ArrayList<>();
        for(FutureTask dealResult: futureList){
            boolean isCancelled = false;
            Future future = dealResult;
            if(!isCancelled){
                try {
                    String result = future.get(5000, TimeUnit.MILLISECONDS);
                    finalResult.add(result);
                }catch (Exception e){
                    System.out.println(e);
                }
            }
        }
        System.out.println("多线程处理完毕.");

        System.out.println("多线程处理结果为:");
        System.out.println(JSON.toJSONString(finalResult));
    }

    private String deal(Integer handler){
        if(handler != null){
            System.out.println("单个线程处理开始:"+handler);
            String str = String.valueOf(handler);
            try{
                Thread.sleep(2000);
            }catch (Exception e){ }
            System.out.println("单个线程处理完毕:"+handler);
            return str;
        }
        return null;
    }
}

可以发现FutureTask是等待所有线程都处理完毕之之后才会继续进行后面的处理,而Future也可以设置超时时间来控制线程处理的时间。

你可能感兴趣的:(JAVA基础功能实例)