前提导入了commons-io-2.6.jar
测试代码如下:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class TestThread2 implements Callable<Boolean> {
String url;
String name;
public TestThread2 (String url, String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
FileLoad1 fileLoad = new FileLoad1();
fileLoad.dowload(url,name);
System.out.println("图片下载成功了!!!");
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FileDownLoad t1 = new FileDownLoad("http://img.alicdn.com/tfscom/i1/821121421/O1CN012nazhz1MMrI77IGuX_!!821121421.jpg_250x250xz.jpg","9.jpg");
FileDownLoad t2 = new FileDownLoad("http://gw.alicdn.com/bao/uploaded/TB1JJgEj8r0gK0jSZFnSuvRRXXa.jpg_440x440q75","10.jpg");
//设置线程池大小
ExecutorService executorService = Executors.newFixedThreadPool(2);
//提交执行
Future<Boolean> s1 = (Future<Boolean>) executorService.submit(t1);
Future<Boolean> s2 = (Future<Boolean>) executorService.submit(t2);
//获取执行结果
Boolean aBoolean = s1.get();
Boolean bBoolean = s2.get();
//关闭服务
executorService.shutdownNow();
}
}
class FileLoad1 {
public void dowload(String url, String name){
try{
FileUtils.copyURLToFile(new URL(url),new File(name));
}catch (IOException e){
e.printStackTrace();
System.out.println("IO异常!!!");
}
}
}