java_使用线程池下载图片

public class ThreadDemo05 implements Callable<Boolean> {
    private String url;//网络图片地址

    private String name;//文件名

    public ThreadDemo05(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public Boolean call() throws Exception {
        WebDownLoaders downLoader = new WebDownLoaders();
        downLoader.downLoader(url,name);
        System.out.println("下载的文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadDemo05 t1 = new ThreadDemo05("图片地址1","1.jpg");
        ThreadDemo05 t2 = new ThreadDemo05("图片地址2","2.jpg");
        ThreadDemo05 t3 = new ThreadDemo05("图片地址3","3.jpg");
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //开始投递任务
        Future<Boolean> r1 = executorService.submit(t1);
        Future<Boolean> r2 = executorService.submit(t2);
        Future<Boolean> r3 = executorService.submit(t3);
        //返回结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        //处理结果
        System.out.println(rs1+"--"+rs2+"--"+rs3);
        //关闭线程池
        executorService.shutdown();
    }


}
class WebDownLoaders {
    //下载
    public void downLoader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            System.out.println("io异常,downloader方法出现问题");
        }
    }

}

 

posted @ 2020-09-01 09:14  阿_闯  阅读(458)  评论(0编辑  收藏  举报