导入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
创建Thread1 类 实现多线程下载文件
public class Thread1 implements Callable<Boolean> {
//网络地址
private String url;
//保存的文件名
private String name;
public Thread1(String url, String name) {
this.url = url;
this.name = name;
}
//下载文件的线程执行体
@Override
public Boolean call() {
FileDownLoader fileDownLoader = new FileDownLoader();
fileDownLoader.downLoader(url,name);
System.out.println("下载了文件名为:" + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread1 t1 = new Thread1("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1887333225,3220403259&fm=26&gp=0.jpg","紫霞仙子.jpg");
Thread1 t2 = new Thread1("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1115306696,372850764&fm=26&gp=0.jpg","冰霜恋舞曲.jpg");
Thread1 t3 = new Thread1("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3005655293,1504161907&fm=26&gp=0.jpg","元素使.jpg");
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> f1 = service.submit(t1);
Future<Boolean> f2 = service.submit(t2);
Future<Boolean> f3 = service.submit(t3);
//获取结果
Boolean rs1 = f1.get();
Boolean rs2 = f2.get();
Boolean rs3 = f3.get();
//关闭服务
service.shutdown();
}
}
//下载器
class FileDownLoader{
// 下载方法
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方法出错");
}
}
}
Callable的的优点: