多线程下载图片
package test2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
public class TestCallable implements Callable<Boolean>{
private String url;
private String filename;
public TestCallable(String url,String filename){
this.url=url;
this.filename=filename;
}
@Override
public Boolean call() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,filename);
System.out.println("图片下载结束名字为"+filename);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1=new TestCallable("http://www.whxzn.com/images/banner/shouhou.jpg","1.jpg");
TestCallable t2=new TestCallable("http://www.whxzn.com/images/faq/1.jpg","2.jpg");
TestCallable t3=new TestCallable("http://www.whxzn.com/images/faq/3.jpg","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 rs1 = r1.get();
Boolean rs2=r2.get();
Boolean rs3=r3.get();
//关闭服务
ser.shutdownNow();
}
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String filename){
try {
FileUtils.copyURLToFile(new URL(url),new File(filename));
} catch (IOException e) {
e.printStackTrace();
System.out.println("io异常");
}
}
}