JAVA多线程读取同一个文件,加速对文件内容的获取

 前几天,朋友托我帮个忙,问我能不能用多线程的方式,读取一个文件,获取里面的内容。他大概想做的事情,就是读取文件里面每一行的内容,然后分析一下,再插入到数据库这样。但是,由于他那个记录内容的文件实在是太大了,虽然他弄成了单生产者-多消费者的模型,整体的处理速度还是非常的慢,因为读取速度不够快。所以,他就问我要怎么多线程读取同一个文件里面的内容,形成多生产者-多消费者的模型,从而提高速度。

  因此就有了下面的demo试的代码,只要传一个文件路径,读取文件的线程数,分隔符,回调这4个参数即可,并且还配上了测试代码。


 下面是我本地跑出来的测试结果(测试文件,是一个190MB大的文件):

3线程(本机2核4线程) 耗时 3231498毫秒
2线程 耗时 278592毫秒
单线程 耗时397115毫秒
cpu线程数(4线程)耗时245657 毫秒


[java]  view plain  copy
  1. package demo.demo;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.RandomAccessFile;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.security.InvalidParameterException;  
  9. import java.util.Random;  
  10. import java.util.UUID;  
  11. import java.util.concurrent.ExecutorService;  
  12. import java.util.concurrent.Executors;  
  13. import java.util.concurrent.atomic.AtomicInteger;  
  14.   
  15. public class ThreadReadFileHelper {  
  16.     // 模拟数据  
  17.     private static void writeData() throws FileNotFoundException, IOException {  
  18.         FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\lianghaohui\\Desktop\\test.txt");  
  19.         Random random = new Random();  
  20.         for (int n = 0; n < 1000000; n++) {  
  21.             int count = random.nextInt(10) + 1;  
  22.             StringBuilder builder = new StringBuilder();  
  23.   
  24.             for (int i = 0; i < count; i++) {  
  25.                 builder.append(UUID.randomUUID().toString());  
  26.             }  
  27.   
  28.             builder.append("\n");  
  29.             fileOutputStream.write(builder.toString().getBytes());  
  30.         }  
  31.         fileOutputStream.close();  
  32.         System.out.println("ok");  
  33.     }  
  34.   
  35.     private static AtomicInteger atomicInteger = new AtomicInteger(0);  
  36.   
  37.     // 231498耗时 3线程(本机2核4线程)  
  38.     // 278592耗时 2线程  
  39.     // 397115耗时 单线程  
  40.     // 245657耗时 cpu线程数(4线程)  
  41.     public static void main(String[] args) throws Exception {  
  42.         long beginTime = System.currentTimeMillis();  
  43.         ThreadReadFileHelper helper = new ThreadReadFileHelper();  
  44.         helper.read("C:\\Users\\lianghaohui\\Desktop\\test.txt", Runtime.getRuntime().availableProcessors(), '\n'new StringCallback("UTF-8") {  
  45.             @Override  
  46.             void callback(String data) {  
  47.                 int count = atomicInteger.incrementAndGet();  
  48.                 System.out.println(count);  
  49.                 if (count == 1000000) {  
  50.                     System.out.println("总耗时毫秒:" + (System.currentTimeMillis() - beginTime));  
  51.                     System.out.println(data);  
  52.                 }  
  53.             }  
  54.         });  
  55.   
  56.         // RandomAccessFile randomAccessFile = new RandomAccessFile("C:\\Users\\lianghaohui\\Desktop\\test.txt", "r");  
  57.         // while (true) {  
  58.         // if (randomAccessFile.readLine() == null) {  
  59.         // System.out.println("总耗时毫秒:" + (System.currentTimeMillis() - beginTime));  
  60.         // break;  
  61.         // } else {  
  62.         // int count = atomicInteger.incrementAndGet();  
  63.         // System.out.println(count);  
  64.         // }  
  65.         // }  
  66.         // randomAccessFile.close();  
  67.     }  
  68.   
  69.     public void read(String path, int threadCount, char separator, StringCallback callback) throws IOException {  
  70.   
  71.         if (threadCount < 1) {  
  72.             throw new InvalidParameterException("The threadCount can not be less than 1");  
  73.         }  
  74.   
  75.         if (path == null || path.isEmpty()) {  
  76.             throw new InvalidParameterException("The path can not be null or empty");  
  77.         }  
  78.   
  79.         if (callback == null) {  
  80.             throw new InvalidParameterException("The callback can not be null");  
  81.         }  
  82.   
  83.         RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");  
  84.   
  85.         long fileTotalLength = randomAccessFile.length();  
  86.         long gap = fileTotalLength / threadCount;  
  87.         long checkIndex = 0;  
  88.         long[] beginIndexs = new long[threadCount];  
  89.         long[] endIndexs = new long[threadCount];  
  90.   
  91.         for (int n = 0; n < threadCount; n++) {  
  92.             beginIndexs[n] = checkIndex;  
  93.             if (n + 1 == threadCount) {  
  94.                 endIndexs[n] = fileTotalLength;  
  95.                 break;  
  96.             }  
  97.             checkIndex += gap;  
  98.             long gapToEof = getGapToEof(checkIndex, randomAccessFile, separator);  
  99.   
  100.             checkIndex += gapToEof;  
  101.             endIndexs[n] = checkIndex;  
  102.         }  
  103.   
  104.         ExecutorService executorService = Executors.newFixedThreadPool(threadCount);  
  105.         executorService.execute(() -> {  
  106.             try {  
  107.                 readData(beginIndexs[0], endIndexs[0], path, randomAccessFile, separator, callback);  
  108.             } catch (Exception e) {  
  109.                 e.printStackTrace();  
  110.             }  
  111.         });  
  112.   
  113.         for (int n = 1; n < threadCount; n++) {  
  114.             long begin = beginIndexs[n];  
  115.             long end = endIndexs[n];  
  116.             executorService.execute(() -> {  
  117.                 try {  
  118.                     readData(begin, end, path, null, separator, callback);  
  119.                 } catch (Exception e) {  
  120.                     e.printStackTrace();  
  121.                 }  
  122.             });  
  123.         }  
  124.     }  
  125.   
  126.     private long getGapToEof(long beginIndex, RandomAccessFile randomAccessFile, char separator) throws IOException {  
  127.         randomAccessFile.seek(beginIndex);  
  128.         long count = 0;  
  129.   
  130.         while (randomAccessFile.read() != separator) {  
  131.             count++;  
  132.         }  
  133.   
  134.         count++;  
  135.   
  136.         return count;  
  137.     }  
  138.   
  139.     private void readData(long begin, long end, String path, RandomAccessFile randomAccessFile, char separator, StringCallback callback) throws FileNotFoundException, IOException {  
  140.         System.out.println("开始工作" + Thread.currentThread().getName());  
  141.         if (randomAccessFile == null) {  
  142.             randomAccessFile = new RandomAccessFile(path, "r");  
  143.         }  
  144.   
  145.         randomAccessFile.seek(begin);  
  146.         StringBuilder builder = new StringBuilder();  
  147.   
  148.         while (true) {  
  149.             int read = randomAccessFile.read();  
  150.             begin++;  
  151.             if (separator == read) {  
  152.                 if (callback != null) {  
  153.                     callback.callback0(builder.toString());  
  154.                 }  
  155.                 builder = new StringBuilder();  
  156.             } else {  
  157.                 builder.append((char) read);  
  158.             }  
  159.   
  160.             if (begin >= end) {  
  161.                 break;  
  162.             }  
  163.         }  
  164.         randomAccessFile.close();  
  165.     }  
  166.   
  167.     public static abstract class StringCallback {  
  168.         private String charsetName;  
  169.         private ExecutorService executorService = Executors.newSingleThreadExecutor();  
  170.   
  171.         public StringCallback(String charsetName) {  
  172.             this.charsetName = charsetName;  
  173.         }  
  174.   
  175.         private void callback0(String data) {  
  176.             executorService.execute(() -> {  
  177.                 try {  
  178.                     callback(new String(data.getBytes("ISO-8859-1"), charsetName));  
  179.                 } catch (UnsupportedEncodingException e) {  
  180.                     e.printStackTrace();  
  181.                 }  
  182.             });  
  183.   
  184.         }  
  185.   
  186.         abstract void callback(String data);  
  187.     }  
  188.   
  189. }  
转自: http://blog.csdn.net/u014653197/article/details/78136568(非常感谢原创博主的整理)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值