图片下载、渲染操作 小例子 看多FutureTask

并发执行下载图片操作

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import com.sun.scenario.effect.ImageData;

public class Renderer {
    
    private final ExecutorService executor;

    public Renderer(ExecutorService executor) {
        this.executor = executor;
    }
    
    void renderPage(CharSequence source) {
        List<ImageInfo> info = scanForImageInfo(executor);
        CompletionService<ImageData> completionService = new ExecutorCompletionService<>(executor);
        for(final ImageInfo imageInfo : info) {
            completionService.submit(new Callable<ImageData>() {
                @Override
                public ImageData call() throws Exception {
                    return imageInfo.downloadImage(); //每张图片并发下载
                }
            });
        }
        renderText(source);
        
        try {
            for(int t = 0,n = info.size(); t < n; t++) {
                Future<ImageData> f = completionService.take();
                ImageData imageData = f.get(); //每下载完一张遍加载渲染一张到页面
                renderImage(imageData);
            }
        } catch(InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
    }

}
原文地址:https://www.cnblogs.com/guchunchao/p/10685446.html