网站建设需要域名吗?,免费做公司电子画册的网站,地方电商门户网站如何建设方案,wordpress 评论 验证码从我 上一篇 关于java.util.concurrent包的 文章 的结尾处 摘下来 #xff0c;这很有趣#xff0c;有时甚至必须在并发任务启动后从它们那里获得反馈。 例如#xff0c;假设一个应用程序必须发送电子邮件批处理#xff0c;除了使用多线程机制外#xff0c;您还想知道成功发… 从我 上一篇 关于java.util.concurrent包的 文章 的结尾处 摘下来 这很有趣有时甚至必须在并发任务启动后从它们那里获得反馈。 例如假设一个应用程序必须发送电子邮件批处理除了使用多线程机制外您还想知道成功发送了多少预期的电子邮件以及在实际发送过程中整个邮件的实时进度批量。 为了实现带有反馈的这种多线程我们可以使用 Callable 接口。 该接口的工作方式与 Runnable 大致相同 但是执行方法call返回的值应反映所执行计算的结果。 让我们首先定义将执行实际任务的类 package com.ricardozuasti;import java.util.concurrent.Callable;public class FictionalEmailSender implements CallableBoolean {public FictionalEmailSender (String to, String subject, String body){this.to to;this.subject subject;this.body body;}Overridepublic Boolean call() throws InterruptedException {// Simulate that sending the email takes between 0 and 0.5 secondsThread.sleep(Math.round(Math.random()* 0.5 * 1000));// Lets say we have an 80% chance of successfully sending our emailif (Math.random()0.2){return true;} else {return false;}}private String to;private String subject;private String body;
} 请注意 Callable可以使用任何返回类型因此您的任务可以返回所需的任何信息。 现在我们可以使用线程池ExecutorService发送电子邮件并且由于我们的任务是作为Callable实现的因此对于提交给执行的每个新任务我们都会获得Future参考。 请注意我们将使用直接构造函数而不是Executors中的实用程序方法来创建ExecutorService 这是因为使用特定类 ThreadPoolExecutor 提供了一些方便的方法在ExecutorService接口中不存在。 package com.ricardozuasti;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class Concurrency2 {public static void main(String[] args) {try {ThreadPoolExecutor executor new ThreadPoolExecutor(30, 30, 1, TimeUnit.SECONDS,new LinkedBlockingQueue());ListFutureBoolean futures new ArrayListFutureBoolean(9000);// Lets spam every 4 digit numeric user on that silly domainfor (int i 1000; i 10000; i) {futures.add(executor.submit(new FictionalEmailSender(i wesellnumericusers.com,Knock, knock, Neo, The Matrix has you...)));}// All tasks have been submitted, wen can begin the shutdown of our executorSystem.out.println(Starting shutdown...);executor.shutdown();// Every second we print our progresswhile (!executor.isTerminated()) {executor.awaitTermination(1, TimeUnit.SECONDS);int progress Math.round((executor.getCompletedTaskCount() * 100) /executor.getTaskCount());System.out.println(progress % done ( executor.getCompletedTaskCount() emails have been sent).);}// Now that we are finished sending all the emails, we can review the futures// and see how many were successfully sentint errorCount 0;int successCount 0;for (FutureBoolean future : futures) {if (future.get()) {successCount;} else {errorCount;}}System.out.println(successCount emails were successfully sent, but errorCount failed.);} catch (Exception ex) {ex.printStackTrace();}}
} 在将所有任务提交给ExecutorService之后 我们开始关闭它防止提交新任务并使用循环在实际情况下如果可能您应该继续执行其他操作等待所有任务完成然后进行计算并打印到目前为止每次迭代的进度。 请注意您可以随时存储执行程序引用并从其他线程查询它以计算和报告流程进度。 最后使用对每个提交给ExecutorService的 Callable的Future引用的集合我们可以告知成功发送的电子邮件数量和失败的电子邮件数量。 这种基础结构不仅易于使用而且还可以促进关注点的清晰分离从而在调度程序和实际任务之间提供了预定义的通信机制。 参考 Java并发示例–在Ricardo Zuasti的博客博客中从我们的JCG合作伙伴 Ricardo Zuasti 获得并发任务的反馈 。 翻译自: https://www.javacodegeeks.com/2012/06/java-concurrency-feedback-from-tasks.html