实现Callable接口
案例:
package com.mokuiran.thread;标签:Callable,name,url,CallableDemo,---,import,new,多线程,String From: https://www.cnblogs.com/mokuiran/p/16661917.html
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三:实现callable接口
public class CallableDemo implements Callable<Boolean> {
private String url;//网络图片的地址
private String name;//保存的文件名
public CallableDemo(String url, String name){
this.url = url;
this.name = name;
}
@Override
public 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 {
CallableDemo demo1 = new CallableDemo("/i/l/?n=22&i=blog/2941481/202207/2941481-20220730105748137-1136505936.png","代码.png");
CallableDemo demo2 = new CallableDemo("/i/l/?n=22&i=blog/2941481/202207/2941481-20220730105748137-1136505936.png","代码2.png");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(2);
//提交执行
Future<Boolean> r1 = ser.submit(demo1);
Future<Boolean> r2 = ser.submit(demo2);
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.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("异常,downloader()方法出现问题");
}
}
}