Java多线程实现100个文件中N行数生成和累加
文件夹下有100个文件,每个文件内有N行数字,使用多线程计算所有文件的数字之和。
首先创建一个测试目录并生成100个文件,每个文件有100行数据,一行只有一个整数。
多线程生成100个含有1000个整数的文件
public class FileOperate {
//向单个文件内写入一百个1000以内的随机数
public static Runnable write(String path) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
Random random = new Random();
for(int i = 0; i < 100; ++i){
int data = random.nextInt(1000);
bw.write(String.valueOf(data));
bw.newLine();
}
bw.close();
return null;
}
//创建目录
public static boolean createDir(String path) {
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
if(dir.exists()){
return true;
}
return false;
}
//在某个目录中生成100个文件
public static void createData(String dir) throws IOException {
createDir(dir);
ExecutorService service = new ThreadPoolExecutor(10, 20, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(10, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
for(int i = 0; i < 100; ++i){
String path = dir + "/" + i + ".txt";
service.execute(() -> {
try {
write(path);
} catch (IOException e) {
e.printStackTrace();
}
});
}
service.shutdown();
}
public static void main(String[] args) throws IOException {
String dir = "D:/test";
createData(dir);
}
}
关于线程池代码:
new ThreadPoolExecutor(10, 20, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(10, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
new ThreadPoolExecutor 的接口如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
int corePoolSize: 核心线程数
int maximumPoolSize, 最大线程数
long keepAliveTime, 非核心线程存活时间
TimeUnit unit, 非核心线程存活时间单位
BlockingQueue<> workQueue, 当线程全部在工作时,任务队列存放多余的任务
ThreadFactory threadFactory, 线程工厂,用于创建线程
RejectedExecutionHandler handler 拒绝策略,当任务太多时的拒绝方法
线程池相当于一个公司,核心线程数(corePoolSize)相当于公司的正式员工,不管公司有没有业务,他们都在公司里待着。
而最大线程数(maximumPoolSize)相当于公司最大可以招纳的员工数,当正式员工不够用时,开始招聘临时工,临时工能在公司待的时间就是 keepAliveTime/unit,keepAliveTime 是数字,unit是单位。
当公司的业务过多时,所有的员工都有活干了,多出来的任务就要存在在任务队列(workQueue)里面,等待员工空闲,
线程工厂(threadFactory)决定员工怎么干活。
当任务队列放满了并且公司的有活干的员工以达到最大数,同时不能再找人了的时候,就要想办法拒绝掉新的业务,拒绝策略(RejectedExecutionHandler)决定了公司的拒绝方式。
读取目录并累加当前目录中所有文件的所有数字。
线程池累加方法一
只使用线程池
import java.io.*;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class FileOperate {
//读取单个文件内数字并累加
public static int read(File file) throws IOException {
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
sum += Integer.parseInt(line);
}
br.close();
return sum;
}
//多线程读取目录下所有文件,并累加每个文件的和
public static void readData(String dir) {
ExecutorService service = new ThreadPoolExecutor(2, Runtime.getRuntime().availableProcessors(), 1, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
File[] files = new File(dir).listFiles();
AtomicInteger tatol = new AtomicInteger();
for(File file : files){
service.execute(() -> {
try {
int sum = read(file);
tatol.addAndGet(sum);
System.out.println(Thread.currentThread().getName() + " 计算文件"+ file.getName() +"的累加和为: " + sum);
} catch (IOException e) {
e.printStackTrace();
}
});
}
files.clone();
service.shutdown();
System.out.println("总数为: " + tatol);
}
public static void main(String[] args) throws IOException {
String dir = "D:/test";
readData(dir);
}
}
线程池累加方法二
使用线程池和common-io-2.6.jar结合的方式
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Test2 implements Runnable {
AtomicInteger num= new AtomicInteger();
CountDownLatch cdl;
@Override
public void run() {
read();
File[] files = new File("D:\\test").listFiles();
cdl = new CountDownLatch(files.length);
ExecutorService executor = new ThreadPoolExecutor(2, Runtime.getRuntime().availableProcessors(), 10,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
//遍历每个文件
for (File f : files) {
executor.execute(()->{
try {
num.addAndGet(readDate(f));
} catch (IOException e) {
e.printStackTrace();
}
cdl.countDown();
});
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(num+"========================================");
executor.shutdown();
files.clone();
}
//读取单个文件并累加所有数字之和
public static int readDate(File f) throws IOException {
int result = 0;
//使用readLines方法,一次读取一行
for (String s : FileUtils.readLines(f, "utf-8")) {
if (s != null) {
result += Integer.parseInt(s);
}
}
System.out.println(Thread.currentThread().getName() + "计算文件"+f.getName()+"和为:" + result);
return result;
}
//无线程测试数据总和
public static void read(){
int n = 0;
File[] files = new File("D:\\test").listFiles();
//遍历每个文件
for (File f : files) {
try {
n += readDate(f);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(n+"========================================read()");
files.clone();
}
}
测试
public class Main {
public static void main(String[] args) {
Test2 t = new Test2();
t.run();
}
}
AtomicInteger:一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。
CountDownLatch有一个整数new CountDownLatch(files.length),用于倒计时,当整数不等于0时,将主线程拒绝再门外,等待其他的线程都执行完任务。