欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java利用CountDownLatch实现并行计算

程序员文章站 2024-03-31 13:20:34
本文实例为大家分享了利用countdownlatch实现并行计算的具体代码,供大家参考,具体内容如下 import java.util.concurrent.co...

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

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