使用Callable来改写图片下载项目
//使用Callable来改写图片下载项目
public class CallableTest implements Callable<Boolean> {
private String url; //网络地址
private String name; //文件名
public CallableTest(String url,String name){
this.url = url;
this.name = name;
}
//下载图片的执行体
@Override
public Boolean call() {
WebDownLoad webDownLoad = new WebDownLoad();
webDownLoad.downLoad(url,name);
System.out.println("文件名:"+name);
return true;
}
//练习:Thread ,实现多线程下载图片
public static void main(String[] args) throws Exception{
CallableTest th1 = new CallableTest("https://img.yalayi.net/d/file/2020/07/24/b6c4ac6b58124d7ac70344ea4992ab5d.jpg","xg1.jpg");
CallableTest th2 = new CallableTest("https://img.yalayi.net/d/file/2020/06/22/13c501bca19b48eb558b4147493330f4.jpg","xg2.jpg");
CallableTest th3 = new CallableTest("https://img.yalayi.net/d/file/2020/06/22/f49a10d2884df025bba6ced8e50cfa2f.jpg","xg3.jpg");
//下载次序每次都会不同
//创建执行服务 开启线程池:3为线程池数量
ExecutorService ser= Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> future1=ser.submit(th1);
Future<Boolean> future2=ser.submit(th2);
Future<Boolean> future3=ser.submit(th3);
//获取结果
boolean flag1= future1.get();
boolean flag2= future2.get();
boolean flag3= future2.get();
System.out.println(flag1);
System.out.println(flag2);
System.out.println(flag3);
//关闭服务
ser.shutdownNow();
}
}
class WebDownLoad{
//下载方法
public void downLoad(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downLoad方法");
}
}
}