package com.hiberate.huijpa;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Client {
private int[] nums;
public Client(int nums) {
this.nums = new int[nums];
}
public int calc(String line, int index, CountDownLatch latch){
String[] nus = line.split(",");
int total=0;
for (String num : nus) {
total += Integer.parseInt(num);
}
System.out.println(Thread.currentThread()+" 结果:"+total);
nums[index] = total;
latch.countDown();
return total;
}
public int sum(){
int total=0;
for (int num : nums) {
total += num;
}
return total;
}
public static void main(String[] args) {
List<String> content = getContent();
Client client = new Client(content.size());
CountDownLatch latch=new CountDownLatch(content.size());
for (int i = 0; i < content.size(); i++) {
final int j=i;
new Thread(new Runnable() {
@Override
public void run() {
client.calc(content.get(j),j,latch);
}
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
int sum = client.sum();
System.out.println("总结果;"+sum);
}
private static List<String> getContent(){
BufferedReader br =null;
List<String> content=new ArrayList<>();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\work\\nums.txt")));
String line=null;
while ((line = br.readLine()) != null){
content.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
}