一、实现Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务: ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行: Future result1 = ser.submit(t1);
- 获取结果: boolean r1 = result1 .get()
- 关闭服务: ser.shutdownNow();
二、案例
package com.massimo.thread;import org.apache.commons.io.FileUtils;import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;public class TestThread05 implements Callable<Boolean> {private String url;//网络图片地址private String name;//保存的文件夹public TestThread05(String url , String name){this.url = url;this.name = name;}@Overridepublic Boolean call() {WebDownloader2 webDownloader2 = new WebDownloader2();webDownloader2.downloader(url , name);System.out.println("下载了文件名为:" + name);return true;}public static void main(String[] args) throws ExecutionException, InterruptedException {TestThread05 t1 = new TestThread05("https://www.apache.org/img/support-apache.jpg", "1.jpg");TestThread05 t2 = new TestThread05("https://www.apache.org/img/support-apache.jpg", "2.jpg");TestThread05 t3 = new TestThread05("https://www.apache.org/img/support-apache.jpg", "3.jpg");//创建执行服务ExecutorService ser = Executors.newFixedThreadPool(3);//提交执行Future<Boolean> r1 = ser.submit(t1);Future<Boolean> r2 = ser.submit(t2);Future<Boolean> r3 = ser.submit(t3);//获取结果Boolean rs1 = r1.get();Boolean rs2 = r2.get();Boolean rs3 = r3.get();//关闭服务ser.shutdownNow();}
}//下载器
class WebDownloader2{//下载方法public void downloader(String url , String name){try {FileUtils.copyURLToFile(new URL(url) , new File(name));} catch (IOException e) {e.printStackTrace();System.out.println("IO异常,downloader方法出现问题");}}
}
结果: