java利用CountDownLatch實現(xiàn)并行計算
更新時間:2018年10月15日 15:09:49 作者:crz_pp
這篇文章主要介紹了java利用CountDownLatch實現(xiàn)并行計算,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了利用CountDownLatch實現(xiàn)并行計算的具體代碼,供大家參考,具體內(nèi)容如下
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() + "執(zhí)行計算任務(wù)..." + line + ",結(jié)果為:" + total);
}
public void sum() {
System.out.println("匯總線程開始執(zhí)行...");
int total = 0;
for (int i : nums) {
total += i;
}
System.out.println("匯總線程結(jié)束執(zhí)行...結(jié)果為:" + 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);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Java騷操作之CountDownLatch代碼詳解
- java多線程CountDownLatch與線程池ThreadPoolExecutor/ExecutorService案例
- java并發(fā)編程專題(八)----(JUC)實例講解CountDownLatch
- 詳解java CountDownLatch和CyclicBarrier在內(nèi)部實現(xiàn)和場景上的區(qū)別
- Java線程并發(fā)工具類CountDownLatch原理及用法
- JAVA CountDownLatch(倒計時計數(shù)器)用法實例
- JAVA CountDownLatch與thread-join()的區(qū)別解析
- 淺談java并發(fā)之計數(shù)器CountDownLatch
- JAVA多線程CountDownLatch使用詳解
- Java并發(fā)編程之CountDownLatch源碼解析
相關(guān)文章
使用spring?data的page和pageable如何實現(xiàn)分頁查詢
這篇文章主要介紹了使用spring?data的page和pageable如何實現(xiàn)分頁查詢,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
mybatis-plus分頁查詢?nèi)N方法小結(jié)
本文主要介紹了mybatis-plus分頁查詢?nèi)N方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Spring Cloud Alibaba Nacos Config配置中心實現(xiàn)
這篇文章主要介紹了Spring Cloud Alibaba Nacos Config配置中心實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

