java多线程读取一个文件

来源:互联网 发布:二手车交易发票软件 编辑:程序博客网 时间:2024/06/07 11:32
package thread;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import java.util.concurrent.CountDownLatch;public class ReadFileByThread {    public static void main(String[] args) throws FileNotFoundException {        long startTime = System.currentTimeMillis();        final int thNum = 10;        final String filePath = "C:\\Users\\IBM_ADMIN\\Downloads\\马达加斯加3全篇英文台词3.txt"; //266M        CountDownLatch doneSignal = new CountDownLatch(thNum);        RandomAccessFile []arr = new RandomAccessFile[thNum];        long length = new File(filePath).length();      long everyThread = length/thNum;        long left = length % thNum;        for(int i=0;i<thNum; i++){            arr[i] = new RandomAccessFile(filePath,"rw");            if(i == (thNum-1)){                new ReadFileThread(everyThread * i,everyThread*(i+1) + left,arr[i],doneSignal).start();            }else{                new ReadFileThread(everyThread * i,everyThread*(i+1),arr[i],doneSignal).start();            }        }        try {            doneSignal.await();        } catch (InterruptedException e) {            e.printStackTrace();        }        long endTime = System.currentTimeMillis();        System.out.println("The totally executed time: "+(endTime-startTime));    }}class ReadFileThread extends Thread{    private long start;    private long end;    private RandomAccessFile raf;    private CountDownLatch doneSignal;    private final int bufLen = 256;    public ReadFileThread(long start,long end,RandomAccessFile raf, CountDownLatch doneSignal){        this.start = start;        this.end = end;        this.raf = raf;        this.doneSignal = doneSignal;    }    @Override    public void run() {        try {            raf.seek(start);            long contentLen = end - start;            long times = contentLen / bufLen +1;            byte []buff = new byte[bufLen];            int hasRead = 0;            String result = null;           for(int i=0;i<times;i++){                hasRead = raf.read(buff);                if(hasRead < 0){                    break;                }                result = new String(buff,"gb2312");         }            doneSignal.countDown();        } catch (IOException e) {            e.printStackTrace();        }    }}

程序说明:

将文件分成10份,每份由一个线程读取。读取完文件计算总时间。

运行结果:

The totally executed time: 2374

说明:此程序是参考其它程序改写,抱歉原文已经找不到了。

0 0
原创粉丝点击