java并行出来文件_Java并行文件处理

我有以下代码:

import java.io.*;

import java.util.concurrent.* ;

public class Example{

public static void main(String args[]) {

try {

FileOutputStream fos = new FileOutputStream("1.dat");

DataOutputStream dos = new DataOutputStream(fos);

for (int i = 0; i < 200000; i++) {

dos.writeInt(i);

}

dos.close(); // Two sample files created

FileOutputStream fos1 = new FileOutputStream("2.dat");

DataOutputStream dos1 = new DataOutputStream(fos1);

for (int i = 200000; i < 400000; i++) {

dos1.writeInt(i);

}

dos1.close();

Exampless.createArray(200000); //Create a shared array

Exampless ex1 = new Exampless("1.dat");

Exampless ex2 = new Exampless("2.dat");

ExecutorService executor = Executors.newFixedThreadPool(2); //Exexuted parallaly to cont number of matches in two file

long startTime = System.nanoTime();

long endTime;

Future future1 = executor.submit(ex1);

Future future2 = executor.submit(ex2);

int count1 = future1.get();

int count2 = future2.get();

endTime = System.nanoTime();

long duration = endTime - startTime;

System.out.println("duration with threads:"+duration);

executor.shutdown();

System.out.println("Matches: " + (count1 + count2));

startTime = System.nanoTime();

ex1.call();

ex2.call();

endTime = System.nanoTime();

duration = endTime - startTime;

System.out.println("duration without threads:"+duration);

} catch (Exception e) {

System.err.println("Error: " + e.getMessage());

}

}

}

class Exampless implements Callable {

public static int[] arr = new int[20000];

public String _name;

public Exampless(String name) {

this._name = name;

}

static void createArray(int z) {

for (int i = z; i < z + 20000; i++) { //shared array

arr[i - z] = i;

}

}

public Object call() {

try {

int cnt = 0;

FileInputStream fin = new FileInputStream(_name);

DataInputStream din = new DataInputStream(fin); // read file and calculate number of matches

for (int i = 0; i < 20000; i++) {

int c = din.readInt();

if (c == arr[i]) {

cnt++;

}

}

return cnt ;

} catch (Exception e) {

System.err.println("Error: " + e.getMessage());

}

return -1 ;

}

}

我在哪里尝试用两个文件计算数组中的匹配数.现在,虽然我在两个线程上运行它,代码表现不佳,因为:

(在单线程上运行,文件1文件2读取时间)< (文件1 ||文件2在多个线程中读取时间). 任何人都可以帮我解决这个问题(我有2个核心CPU,文件大小约为1.5 GB).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值