package com.Test;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//开启线程方式三:实现Callable接口
//实现Callable的好处
//可以抛出异常
//可以获取返回值
标签:name,TestCallable,接口,Callable,url,jpg,new,多线程,String From: https://www.cnblogs.com/fc666/p/17145728.html
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url,String name){
this.url=url;
this.name=name;
}
@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 thread1 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/04.jpg","4.jpg");
TestCallable thread2 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/05.jpg","5.jpg");
TestCallable thread3 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/06.jpg","6.jpg");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(thread1);
Future<Boolean> r2 = ser.submit(thread2);
Future<Boolean> r3 = ser.submit(thread3);
// 获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
// 关闭服务
ser.shutdownNow();
}
// 下载器
class WebDownLoader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载器有问题,downloader方法有bug");
}
}
}
}