步骤
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
这是一个线程池,3,代表这个线程池里面可以有三个线程 - 提交执行
Future t1 = executorService.submit(testThread01); - 获取结果
Boolean Boolean1 = t1.get(); - 关闭服务
executorService.shutdown();
package com.yf.demo02;
import com.yf.demo1.TestThread01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class TestCallable implements Callable<Boolean> {
private String name;
private String url;
public TestCallable(String url,String name){
this.name = name;
this.url = url;
}
@Override
public Boolean call() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downLoader(url,name);
System.out.println("下载了,文件名为"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testThread01 = new TestCallable("https://maven.apache.org/images/maven-logo-black-on-white.png","1.jpg");
TestCallable testThread02 = new TestCallable("https://maven.apache.org/images/apache-maven-project.png","2.jpg");
TestCallable testThread03 = new TestCallable("https://maven.apache.org/images/logos/maven-feather.png","3.jpg");
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<Boolean> t1 = executorService.submit(testThread01);
Future<Boolean> t2 = executorService.submit(testThread02);
Future<Boolean> t3 = executorService.submit(testThread03);
Boolean Boolean1 = t1.get();
Boolean Boolean2 = t2.get();
Boolean Boolean3 = t3.get();
executorService.shutdown();
}
}
class WebDownLoader{
public void downLoader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}