方法说明:
/**
* Executes the given tasks, returning a list of Futures holding
* their status and results when all complete.
* {@link Future#isDone} is {@code true} for each
* element of the returned list.
* Note that a <em>completed</em> task could have
* terminated either normally or by throwing an exception.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*
* @param tasks the collection of tasks
* @param <T> the type of the values returned from the tasks
* @return a list of Futures representing the tasks, in the same
* sequential order as produced by the iterator for the
* given task list, each of which has completed
* @throws InterruptedException if interrupted while waiting, in
* which case unfinished tasks are cancelled
* @throws NullPointerException if tasks or any of its elements are {@code null}
* @throws RejectedExecutionException if any task cannot be
* scheduled for execution
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
运行结果可能出现的情况:
- 全部运行成功
- 部分运行失败,剩余任务被取消
玩具代码:
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; import java.util.concurrent.TimeUnit; //运行多个任务并处理所有结果 public class Result { private String name; private int value; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public static class Task implements Callable<Result>{ private String name; public Task(String name){ this.name = name; } @Override public Result call() throws Exception { System.out.printf("%s : Staring \n", this.name); try{ long duration = (long)(Math.random()*10); System.out.printf("%s:Waiting %d seconds for results . \n", this.name,duration); TimeUnit.SECONDS.sleep(duration); }catch(InterruptedException e){ e.printStackTrace(); } int value = 0; for(int i=0;i<5;i++){ value += (int)(Math.random()*100); } Result result = new Result(); result.setName(name); result.setValue(value); System.out.println(this.name+": Ends"); return result; } } public static void main(String[] args) { ExecutorService executor =(ExecutorService)Executors.newCachedThreadPool(); List<Task> taskList = new ArrayList<>(); for(int i=0;i<3;i++){ Task task = new Task(Integer.toString(i)); taskList.add(task); } List<Future<Result>> resultList = new ArrayList<>(); try { //等待所有任务执行完成 executor.invokeAll(taskList); } catch (InterruptedException e) { e.printStackTrace(); } executor.shutdown(); System.out.printf("Main: Printing the results \n"); for(int i=0;i<resultList.size();i++){ Future<Result> future = resultList.get(i); try{ Result result = future.get(); System.out.printf("%s : %s \n",result.getName(),result.getValue()); }catch(InterruptedException | ExecutionException e){ e.printStackTrace(); } } } }
AbstractExecutorService.invokeAll实现逻辑:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { if (tasks == null) throw new NullPointerException(); ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size()); boolean done = false; try { for (Callable<T> t : tasks) { RunnableFuture<T> f = newTaskFor(t); futures.add(f); execute(f); } for (int i = 0, size = futures.size(); i < size; i++) { Future<T> f = futures.get(i); if (!f.isDone()) { try { f.get(); } catch (CancellationException ignore) { } catch (ExecutionException ignore) { } } } done = true; return futures; } finally { if (!done) for (int i = 0, size = futures.size(); i < size; i++) futures.get(i).cancel(true); } }
相关推荐
NULL 博文链接:https://songjianyong.iteye.com/blog/2056990
16. 执行器服务 ExecutorService 17. 线程池执行者 ThreadPoolExecutor 18. 定时执行者服务 ScheduledExecutorService 19. 使用 ForkJoinPool 进行分叉和合并 20. 锁 Lock 21. 读写锁 ReadWriteLock 22. 原子性布尔 ...
其定义了一个接收Runnable对象的方法executor,其方法签名为executor(Runnable command),该方法接收一个Runable实例,它用来执行一个任务,任务即一个实现了Runnable接口的类,一般来说,Runnable任务开辟在新线程中...
主要介绍了线程并发ScheduledExecutorService类,设置 ScheduledExecutorService ,2秒后,在 1 分钟内每 10 秒钟蜂鸣一次
执行器服务 ExecutorService 17. 线程池执行者 ThreadPoolExecutor 18. 定时执行者服务 ScheduledExecutorService 19. 使用 ForkJoinPool 进行分叉和合并 20. 锁 Lock 21. 读写锁 ReadWriteLock 22. 原子性布尔 ...
运用JAVA的concurrent.ExecutorService线程池实现socket的TCP和UDP连接
JAVA线程基本学习, JAVA多线程的特性= 线程池: 本质上是一个对象池, 用来管理线程资源. 在任务执行前, 需要从线程池中拿出线程来执行. 在任务执行完成之后, 需要把线程放回线程池. 线程池好处: 降低资源的消耗...
25 JAVA8 与元数据.................................................................................................................................25 2.4. 垃圾回收与算法 .................................
主要帮助大家理解java多线程中ExcetorServiced的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在Java SE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表示的是从方法call()中返回的值,并且必须使用ExecutorService.submit()方法调用它。 import java.util.ArrayList; import java.util....
运用JAVA的concurrent.ExecutorService线程池实现socket的TCP和UDP连接.doc
主要介绍了Java使用ExecutorService来停止线程服务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
接口 java.util.concurrent.ExecutorService 表述了异步执行的机制,并且可以让任务在后台执行。壹個 ExecutorService 实例因此特别像壹個线程池。事实上,在 java.util.concurrent 包中的 ExecutorService 的实现...
16. 执行器服务 ExecutorService 17. 线程池执行者 ThreadPoolExecutor 18. 定时执行者服务 ScheduledExecutorService 19. 使用 ForkJoinPool 进行分叉和合并 20. 锁 Lock 21. 读写锁 ReadWriteLock 22. 原子性布尔 ...
这是利用java的udp通信,利用多线程保持通信持续的java聊天小程序
ExecutorService的execute和submit方法
Java多线程入阶干货分享 1.使用线程的经验:设置名称、响应中断、使用ThreadLocal 2.Executor:ExecutorService和Future 3.阻塞队列:put和take、offer和poll、drainTo 4.线程间通信:lock、condition、wait、notify...
看完《think in java》多线程章节,自己写的多线程文档,还结合了其他的相关网络资料。 线程 一. 线程池 1)为什么要使用线程池 2 2)一个具有线程池的工作队列 3 3)使用线程池的风险: 4 4)有效使用线程池的原则 5...
Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点 。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。 线程的概念 线程进程区别 在...
本代码是JAVA 编码,使用多线程泛型例子获取对应多线程返回结果,便于后期扩充,可以改变ExecutorService。