利用多线程实现把一个txt文档里面的所有数字累加
- 线程任务类通过继承Callable接口,并设置返回值是integer的泛型,因为Callable是可以带返回值的,所以就可以把每个线程累加的值返回
public class Task implements Callable<Integer> {
//开始字节数
private Integer pos;
//结束字节数
private Integer len;
public Task(Integer pos, Integer len) {
this.pos = pos;
this.len = len;
}
@Override
public Integer call() throws Exception {
File file = new File("C:\\Users\\user\\Desktop\\numbes.txt");
FileInputStream stream = new java.io.FileInputStream(file);
stream.skip(pos); // 跳过之前的字节数
byte[] b = new byte[len]; //读取的字节长度
stream.read(b);
String numberStr = new String(b);
String[] numbers = numberStr.split("");
Integer sum = 0;
for (String str : numbers) {
if (StringUtils.isNotEmpty(str.trim())) {
//相加每个线程得到的值
sum += Integer.valueOf(str);
}
}
return sum;
}
}
- 主线程这边只需要通过循环去创建任务类并累加字节开始值和结束值,拿到返回参数相加就可以了
public class test {
private static Integer pos=0;
private static Integer len=100;
private static Integer sum=0;
static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
public static void main(String[] args) throws InterruptedException, ExecutionException {
for (int i = 0; i < 10; i++) {
//初始化任务类
Task task1 = new Task(pos, len);
//通过future异步提交任务
Future<Integer> res = executor.submit(task1);
pos=len+1;
len+=100;
//获取线程返回值累加
sum+=res.get();
System.out.println(res.get());
}
System.out.println(sum);
executor.shutdown();
}
}