本文实例为大家分享了利用countdownlatch实现并行计算的具体代码,供大家参考,具体内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://HdhCmsTestcnblogs测试数据/ppcoder/p/9790922.html
查看更多关于java利用CountDownLatch实现并行计算的详细内容...