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); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。