Future是线程与线程间通信的封装
相当于省去了一个公共的共享区static List,以及具有wait和notify通信机制
CompletionService 相当于维护了一组Future
[code]
//Future相当于static List 以及wait,notify机制的结合,用于线程间通信
class Renderer{
private final ExecutorService exector ;
Renderer(ExecutorService exector ){
this.exector = exector;
}
void renderPage(CharSequence source){
final List<ImageInfo> imageInfos = scanForImageInfo(source);
CompletionService<ImageData> completionService=
new ExecutorCompletionService<ImageData>(executor); //CompletionService维护了一个List<Future>
for(final ImageInfo imageInfo:info)
completionService.submit(new Callable<ImageData>() {
public ImageData call(){
return imageInfo.downloadImage();
}
});
renderText(source);
for(int t=0,n=info.size();t<n;t++){
Future<ImageData> f = completionService.take();//Future避免了在外部再定义一个List,他就可以用于线程之间的通信
ImageData imageData = f.get();
renderImage(imageData);
}
}
}
[/code]
相当于省去了一个公共的共享区static List,以及具有wait和notify通信机制
CompletionService 相当于维护了一组Future
[code]
//Future相当于static List 以及wait,notify机制的结合,用于线程间通信
class Renderer{
private final ExecutorService exector ;
Renderer(ExecutorService exector ){
this.exector = exector;
}
void renderPage(CharSequence source){
final List<ImageInfo> imageInfos = scanForImageInfo(source);
CompletionService<ImageData> completionService=
new ExecutorCompletionService<ImageData>(executor); //CompletionService维护了一个List<Future>
for(final ImageInfo imageInfo:info)
completionService.submit(new Callable<ImageData>() {
public ImageData call(){
return imageInfo.downloadImage();
}
});
renderText(source);
for(int t=0,n=info.size();t<n;t++){
Future<ImageData> f = completionService.take();//Future避免了在外部再定义一个List,他就可以用于线程之间的通信
ImageData imageData = f.get();
renderImage(imageData);
}
}
}
[/code]