并发编程之并发工具类CountDownLatch详解

转发自:https://blog.csdn.net/qq_29479041/article/details/85275159

CountDownLatch代码:

//对一个文本中的所有数字先行求和,再把所有行汇总
package com.roocon.thread.tb4;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Demo2 {

	private int[] nums;

	public Demo2(int line) {
		nums = new int[line];
	}

	public void calc(String line, int index, CountDownLatch latch) {
		String[] nus = line.split(","); // 切分出每个值
		int total = 0;
		for (String num : nus) {
			total += Integer.parseInt(num);
		}
		nums[index] = total; // 把计算的结果放到数组中指定的位置
		System.out.println(Thread.currentThread().getName() + " 执行计算任务... " + line + " 结果为:" + total);
		latch.countDown();
	}

	public void sum() {
		System.out.println("汇总线程开始执行... ");
		int total = 0;
		for (int i = 0; i < nums.length; i++) {
			total += nums[i];
		}
		System.out.println("最终的结果为:" + total);
	}

	public static void main(String[] args) {

		List<String> contents = readFile();
		int lineCount = contents.size();
		
		CountDownLatch latch = new CountDownLatch(lineCount);

		Demo2 d = new Demo2(lineCount);
		for (int i = 0; i < lineCount; i++) {
			final int j = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					d.calc(contents.get(j), j, latch);
				}
			}).start();
		}

		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		d.sum();
	}

	private static List<String> readFile() {
		List<String> contents = new ArrayList<>();
		String line = null;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("e:\\nums.txt"));
			while ((line = br.readLine()) != null) {
				contents.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return contents;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值