package www.shushu.demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/*
callable的好处
1.可以定义返回值
2.可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
private String name;
private String url;
public TestCallable(String url, String name) {
this.name = name;
this.url = url;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testCallable = new TestCallable("https://tse3-mm.cn.bing.net/th/id/OIP.1sYdjAro5j4eFreLNVBBCAHaEf?w=307&h=186&c=7&o=5&dpr=1.25&pid=1.7","1.jpg");
TestCallable testCallable2 = new TestCallable("https://tse2-mm.cn.bing.net/th/id/OIP.v-kgJrckGXE3zi7HWAAAqQHaEK?w=331&h=186&c=7&o=5&dpr=1.25&pid=1.7","2.jpg");
TestCallable testCallable3 = new TestCallable("https://tse3-mm.cn.bing.net/th/id/OIP.-iKnMH97MAc-HQS458hNKQHaJ4?w=140&h=186&c=7&o=5&dpr=1.25&pid=1.7","3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> result1 = ser.submit(testCallable);
Future<Boolean> result2 = ser.submit(testCallable2);
Future<Boolean> result3 = ser.submit(testCallable3);
//获取结果
boolean rs1 = result1.get();
boolean rs2 = result2.get();
boolean rs3 = result3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
ser.shutdownNow();
}
@Override
public Boolean call() throws Exception {
WebDownloader webDownloader = new WebDownloader();
try {
webDownloader.downloader(url,name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载好文件:"+name);
return true;
}
}
class WebDownloader{
public void downloader(String url,String name) throws IOException {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
}