package TestCallable;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
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 t1 = new TestCallable("https://i0.hdslb.com/bfs/archive/d84bfd5d474b3b9170b" +
"060f367db162c722cb654.jpg@1100w_484h_1c_100q.jpg","1.jpg");
TestCallable t2 = new TestCallable("https://i0.hdslb.com/bfs/sycp/creative_img/202004/f2" +
"338405fba5c61cfb130794a1501b7c.jpg@1100w_484h_1c_100q.jpg","2.jpg");
TestCallable t3 = new TestCallable("https://i0.hdslb.com/bfs/archive/d3cf0c917f7547bd1f573c" +
"d95a79384e5fcd6992.png@1100w_484h_1c_100q.png","3.jpg");
ExecutorService ser = Executors.newFixedThreadPool(3);
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
boolean rr1 = r1.get();
boolean rr2 = r2.get();
boolean rr3 = 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) {
System.out.println("io异常,downloader方法出现问题!");
}
}
}
图片下载完成
callable可以定义返回值,可以抛出异常