当前位置: 移动技术网 > IT编程>开发语言>Java > java利用CountDownLatch实现并行计算

java利用CountDownLatch实现并行计算

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了利用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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网