CountDownLatch uses small Demo

Suppose we have the following content in another file, and sum them

The general idea is to read the file, how many lines to open and how many threads to calculate, and then summarize. Before summarizing, let the main thread of the summary be blocked, and wait for all the sub threads to complete the calculation before summarizing

package cn.itchao.countdownlatch;

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 CountDownLatchDemo {
	
	private Integer[] nums;//Total number of banks
	
	public CountDownLatchDemo(Integer line){
		nums = new Integer[line];
	}
	
	/**
	 * 
	 * @param lineText Row content
	 * @param index Row number
	 */
	public void calc(String lineText,Integer index){
		String[] numsArray = lineText.split(",");
		Integer total = 0;
		for(String num : numsArray){
			total += Integer.parseInt(num);
		}
		nums[index] = total;
		System.out.println(Thread.currentThread().getName()+"  
                  //The thread starts to calculate... "+ lineText +", and the calculation result is: "+ total";
	}
	
	public void sum(){
		System.out.println("Start execution of summary calculation results.....");
		int total = 0;
		for (int i = 0; i < nums.length; i++) {
			total +=nums[i];
		}
		System.out.println("Final calculation results:"+total);
	}
	
	public static void main(String[] args) {
		List<String> contents = readFile();
		Integer lineNum = contents.size();
		CountDownLatch count = new CountDownLatch(lineNum);//Define a counter
		CountDownLatchDemo demo = new CountDownLatchDemo(lineNum);
		
		for (int i = 0; i < lineNum; i++) {
			final int j = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					demo.calc(contents.get(j), j);
					count.countDown();
				}
			}).start();
		}
		
		//Summary
		try {
			count.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		demo.sum(); 
		
	}


	private static List<String> readFile() {
		List<String> contents = new ArrayList<>();
		String lineText = null;
		BufferedReader bufferedReader = null;
		try {
			String filePath = "/itchao-thread/src/main/resources/nums.txt";
			bufferedReader = new BufferedReader(new FileReader(filePath));
			while((lineText=bufferedReader.readLine())!=null){
				 contents.add(lineText);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(bufferedReader!=null){
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return contents;
	}
	
	

}

Print results:

In the same way, in the real enterprise development, each sheet of the table is read separately, and finally the summary calculation is carried out, which can achieve efficient operation.

Keywords: Java

Added by ziesje on Mon, 06 Jan 2020 04:08:04 +0200