package com.xingfu.wx;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* 获取ReportGenerator任务的结果
* @author W,x
* @version 创建时间:2015年4月14日 上午9:37:46
*
*/
public class ReportProcessor implements Runnable {
private CompletionService<String> service;
private boolean end;
public ReportProcessor(CompletionService<String> service) {
super();
this.service = service;
}
@Override
public void run() {
//如果end属性值为false,则调用CompletionService接口的poll()方法,来获取下一个经完成任务的Future对象
while(!end){
try {
//调用poll()方法时传递了两个参数,标识当队列里完成任务的结果为空,想要等待任务执行结束的时间
Future<String> result = service.poll(20, TimeUnit.SECONDS);
if(result!=null){
String report=result.get();
Utils.print("ReportReceiver: Report Received: %s\n",report);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
Utils.print("ReportSender : End\n");
}
public void setEnd(boolean end){
this.end=end;
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
//创建一个完成服务
CompletionService<String> service=new ExecutorCompletionService<>(executor);
//创建两个ReportRequest对象,然后创建两个线程Thread对象分别来执行他们
ReportReuest faceRequest = new ReportReuest("Face", service);
ReportReuest onlineReuest= new ReportReuest("Online", service);
Thread faceThread=new Thread(faceRequest);
Thread onlineThread=new Thread(onlineReuest);
//创建个ReportProcessor对象,然后创建一个线程Thread对象来执行它
ReportProcessor processor=new ReportProcessor(service);
Thread senderThread=new Thread(processor);
Utils.print("Main : Starting the Threads\n");
faceThread.start();
onlineThread.start();
senderThread.start();
try{
Utils.print("Main:Waiting for the repost generators\n");
faceThread.join();
onlineThread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
Utils.print("Main:Shuting down the executor.\n");
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
processor.setEnd(true);
Utils.print("Main:Ends");
}
}
通常情况下,使用执行器来执行并发任务时,将runnable或Callable任务发送给执行器,并获得Future对象来控制任务。此外,还回碰到如下情形,需要在一个对象发送任务给执行器,然后在另一个对象里处理结果。对于这种情况,java并发API提供了CompletionService类
CompletionService类有一个方法用来发送任务给执行器,还有一个方法为下一个已经执行结束的任务获得Future对象。从内部实现机制来看,CompletionService类使用Excutor对象来执行任务。这个行为的优势是可以共享CompletionService对象,并发送任务到执行器,然后其他的对象可以处理任务的结果。第二个方法有一个不足之处,它只能为已经执行结束的任务获取Future对象,因此,这些Future对象只能被用来获取任务的结果。
package com.xingfu.wx;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
*
* @author W,x
* @version 创建时间:2015年4月14日 上午9:28:07
*
*/
public class ReportGenerator implements Callable<String> {
private String sender;
private String title;
public ReportGenerator(String sender, String title) {
super();
this.sender = sender;
this.title = title;
}
@Override
public String call() throws Exception {
long duration = (long) (Math.random() * 10);
Utils.print("%s_%s: ReportGenerator: Generating a report during %d seconds\n", this.sender,
this.title, duration);
TimeUnit.SECONDS.sleep(duration);
String ret = sender + ": " + title;
return ret;
}
}
package com.xingfu.wx;
import java.util.concurrent.CompletionService;
/**
* 模拟请求获取报告
*
* @author W,x
* @version 创建时间:2015年4月14日 上午9:33:19
*
*/
public class ReportReuest implements Runnable {
//用来存储ReportRequest的名称
private String name;
private CompletionService<String>service;
public ReportReuest(String name, CompletionService<String> service) {
super();
this.name = name;
this.service = service;
}
@Override
public void run() {
ReportGenerator reportGenerator=new ReportGenerator(name, "report");
service.submit(reportGenerator);
}
}
工作原理
在范例类中,我们调用Executors工厂类的newCachedThreadPool()方法创建了一个ThreadPoolExecutor执行器对象,然后,使用这个对象初始化了CompletionService对象,因为完成服务(Completion Service)使用执行器完成任务,然后,调用ReportReques类中的submit()方法,利用“完成服务”来执行任务。
当完成服务任务结束,这些任务中一个任务就执行结束了,完成服务中存储这Future对象,用来控制它在队列中的执行。
调用poll()方法访问这个队列,查看是否有任务已经完成,如果有,则返回队列中的第一个元素(既一个任务执行完成后的Future对象)。当poll()方法返回Future对象后,它将队列中删除中Future对象。在这个实例中,我们在调用poll()方法时传递了两个参数,标识当队列里完成任务的结果为空,想要等待任务执行结束的时间。
一旦创建了ComletionService对象,还要创建两个ReportRequest对象,用来执行在CompletionService中的两个ReportGenerator任务。ReportProcessor任务则将处理两个被发送到执行器里的ReportRequest任务所产生的结果