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 TestCallabele implements Callable<Boolean> {
private String url; //网络图片地址
private String name; //保存的文件名
public TestCallabele(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 {
TestCallabele t1 = new TestCallabele("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=212643867,613984248&fm=26&gp=0.jpg","时崎狂三1.jpg");
TestCallabele t2 = new TestCallabele("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1903927405,3275277244&fm=26&gp=0.jpg","时崎狂三2.jpg");
TestCallabele t3 = new TestCallabele("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=834800350,283342375&fm=26&gp=0.jpg","时崎狂三3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3) ;
//提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
//获取结果
boolean r1 = result1.get();
boolean r2 = result2.get();
boolean r3 = result3.get();
//打印返回值
// System.out.println(r1);
// System.out.println(r2);
// System.out.println(r3);
//关闭服务
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("IO异常,downloader方法出现问题");
}
}
}
多线程3-实现callable接口
最新推荐文章于 2024-04-02 12:49:51 发布