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();
    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进行并行处理,效率大概提高了将近一倍!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值