通过多个线程读取文件 [英] Reading a file by multiple threads

查看:85
本文介绍了通过多个线程读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个250Mb的文件要读取.并且该应用程序是多线程的.如果我允许所有线程读取文件,则会发生内存不足. 我出现内存不足错误.

I have a 250Mb file to be read. And the application is multi threaded. If i allow all threads to read the file the memory starvation occurs. I get out of memory error.

为避免它.我只想在内存中只有一个String副本(从流中读取),我希望所有线程都可以使用它.

To avoid it. I want to have only one copy of the String (which is read from stream) in memory and i want all the threads to use it.

while (true) {
    synchronized (buffer) {
        num = is.read(buffer);
            String str = new String(buffer, 0, num);

    }
    sendToPC(str);
}

基本上,当所有线程完成发送时,我只希望有一个字符串副本,我想读取第二个字符串,依此类推.

Basically i want to have only one copy of string when all thread completed sending, i want to read second string and so on.

推荐答案

为什么有多个线程?您只有一个磁盘,而且只能运行这么快.几乎可以肯定,多线程将无济于事.而且,任何依赖于在内存中存储整个文件的软件设计都首先存在严重缺陷.

Why multiple threads? You only have one disk and it can only go so fast. Multithreading it won't help, almost certainly. And any software design that relies on having an entire file in memory is seriously flawed in the first place.

假设您定义了问题?

这篇关于通过多个线程读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆