image.png
    Callable 有返回类型
    重写 public Boolean call()方法

    1. package com.pln.callables;
    2. import com.pln.thread.TestThread2;
    3. import org.apache.commons.io.FileUtils;
    4. import java.io.File;
    5. import java.io.IOException;
    6. import java.net.URL;
    7. import java.util.concurrent.*;
    8. public class TestCallable1 implements Callable <Boolean>{
    9. private String url;
    10. private String name;
    11. public TestCallable1(String url,String name){
    12. this.url = url;
    13. this.name = name;
    14. }
    15. @Override
    16. public Boolean call() throws Exception {
    17. WebDownLoader webDownLoader = new WebDownLoader();
    18. webDownLoader.downLoader(url,name);
    19. System.out.println("下载名字+"+name);
    20. return true;
    21. }
    22. public static void main(String[] args) throws ExecutionException, InterruptedException {
    23. // 调用带参的构造方法
    24. TestCallable1 t1 = new TestCallable1("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20196302356495401.jpg","1.jpg");
    25. TestCallable1 t2 = new TestCallable1("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20196302342173219.jpg","2.jpg");
    26. TestCallable1 t3 = new TestCallable1("http://www.mdjdx.cn/mdtpweb/upload/ew/uploadfile/f20198310114727.jpg","3.jpg");
    27. //创建执行服务
    28. ExecutorService ser = Executors.newFixedThreadPool(3);//3代表有三个对象三张图片下载
    29. //提交执行
    30. Future<Boolean> r1 = ser.submit(t1);
    31. Future<Boolean> r2 = ser.submit(t2);
    32. Future<Boolean> r3 = ser.submit(t3);
    33. //获取结果
    34. boolean rs1 = r1.get();
    35. boolean rs2 = r2.get();
    36. boolean rs3 = r3.get();
    37. //关闭服务
    38. ser.shutdownNow();
    39. }
    40. }
    41. //下载器
    42. class WebDownLoader {
    43. // 下载方法
    44. public void downLoader(String url,String name) throws IOException {
    45. FileUtils.copyURLToFile(new URL(url),new File(name));
    46. }
    47. }