适用场景:前提保证线程安全,例如需要将多个文件下载保存到服务器
通常写法:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/4e0ee00927534036af9a9aae1a545af7-1_201908261600517471.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/4e0ee00927534036af9a9aae1a545af7-2.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/d6f0f7d8b5064e47b62f1e13014b92be.jpg");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/85da58f7095043cc815bcb1840544a01-1.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/85da58f7095043cc815bcb1840544a01-1_2.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/94264b3d3e8f4d1bad87397138d07e66.jpg");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/dd7d4342d01f479a85c5951ac034b286.bmp");
long start = System.currentTimeMillis();
for (String s : list) {
UrlFileUtil.downloadFile(s,"/Users/jianglinmao/Downloads/img");
}
long end = System.currentTimeMillis();
System.out.println("运行时间:" + (end - start));
}
运行时间:541毫秒
java8 parallel 处理方法:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/4e0ee00927534036af9a9aae1a545af7-1_201908261600517471.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/4e0ee00927534036af9a9aae1a545af7-2.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/d6f0f7d8b5064e47b62f1e13014b92be.jpg");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/85da58f7095043cc815bcb1840544a01-1.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/85da58f7095043cc815bcb1840544a01-1_2.bmp");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/94264b3d3e8f4d1bad87397138d07e66.jpg");
list.add("http://172.16.140.152:8080/cms1/filePath/Image/2019-08-26/dd7d4342d01f479a85c5951ac034b286.bmp");
long start = System.currentTimeMillis();
list.stream().parallel().forEach(s -> {
UrlFileUtil.downloadFile(s,"/Users/jianglinmao/Downloads/img");
});
long end = System.currentTimeMillis();
System.out.println("运行时间:" + (end - start));
}
运行时间:276毫秒
很明显,通过parallel进行并行处理,效率大概提高了将近一倍!