Erlo

for miaomiao

2019-10-22 18:00:19 发布   332 浏览  
页面报错/反馈
收藏 点赞
package com.mycloud.demo.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public abstract class MultiThreadService {

    public <T, R> List<T> process(List<R> resources, int threadNumber) {

        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        List<Future<T>> futures = new ArrayList<>();

        for (R resource : resources) {
            SubTask<T, R> subTask = new SubTask<>(resource);
            futures.add(executorService.submit(subTask));
        }

        List<T> resultList = new ArrayList<>();
        try {
            for (Future<T> future : futures) {
                if (future.get() != null) {
                    resultList.add(future.get());
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

        return resultList;

    }

    protected abstract <T, R> T doSubTask(R resource);

    private class SubTask<T, R> implements Callable<T> {

        private R resource;

        public SubTask(R resource) {
            this.resource = resource;
        }

        @Override
        public T call() throws Exception {
            return doSubTask(resource);
        }
    }
}

 

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认