评论

收藏

[Java] java利用CountDownLatch实现并行计算

编程语言 编程语言 发布于:2021-10-08 11:40 | 阅读数:341 | 评论:0

这篇文章主要介绍了java利用CountDownLatch实现并行计算,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了利用countdownlatch实现并行计算的具体代码,供大家参考,具体内容如下
import java.util.concurrent.countdownlatch;
 
/**
 * @author pipi
 * @date 2018/10/15 13:56
 **/
public class parallelcomputing {
  private int[] nums;
  private string[] info;
  private countdownlatch countdownlatch;
 
  public parallelcomputing(string[] info) {
  this.info = info;
  int size = info.length;
  nums = new int[size];
  this.countdownlatch = new countdownlatch(size);
  }
 
  public void calc(string line, int index) throws interruptedexception {
  string[] numbers = line.split(",");
  int total = 0;
  for (string num : numbers) {
    total += integer.parseint(num);
  }
  thread.sleep(5000);
  nums[index] = total;
  countdownlatch.countdown();
  system.out.println(thread.currentthread().getname() + "执行计算任务..." + line + ",结果为:" + total);
  }
 
  public void sum() {
  system.out.println("汇总线程开始执行...");
  int total = 0;
  for (int i : nums) {
    total += i;
  }
  system.out.println("汇总线程结束执行...结果为:" + total);
  }
 
  public void calcsum() throws interruptedexception {
  int size = info.length;
  for (int i = 0; i < size; i++) {
    final int j = i;
    new thread(() -> {
    try {
      calc(info[j], j);
    } catch (interruptedexception e) {
      e.printstacktrace();
    }
    }).start();
  }
  countdownlatch.await();
  sum();
  }
 
  public static void main(string[] args) throws interruptedexception {
  long start = system.currenttimemillis();
  string[] info = {
    "2,22",
    "3,33",
    "232,32,76,84",
    "99,45,1"
  };
  parallelcomputing parallelcomputing = new parallelcomputing(info);
  parallelcomputing.calcsum();
  long end = system.currenttimemillis();
  system.out.println(end - start);
  }
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家
原文链接:https://www.cnblogs.com/ppcoder/p/9790922.html

关注下面的标签,发现更多相似文章