java中的多线程

时间:2009-08-12 11:51:31

标签: java multithreading file-io

如果我有一个包含4000个字节的文件,我可以同时从文件中读取4个线程吗?每个线程访问文件的不同部分。

线程1读取0-999,线程2读取1000 - 2999等

请在java中给出一个例子。

5 个答案:

答案 0 :(得分:9)

该文件非常小,加载速度非常快。我要做的是创建一个加载数据的线程安全数据类。然后,每个处理线程都可以从数据类中请求一个ID,并接收一个唯一的ID,保证没有其他线程向您的远程服务发送相同的ID。

通过这种方式,您无需让所有线程访问该文件,并试图找出谁已阅读并发送了什么ID。

答案 1 :(得分:5)

RandomAccessFileFileChannel将允许您访问文件中的字节。要等到线程完成,请查看CyclicBarrierCountDownLatch

答案 2 :(得分:4)

鉴于该问题的作者的评论:

  

我想运行批处理文件,其中   它包含数以千计的唯一ID。   这个每个唯一ID都会发送一个   请求远程系统。所以我   想要并行发送请求   线程加快进程。但   如果使用多线程则所有   线程读取完整的数据和   重复请求正在发送。所以我   我想避免这种重复的请求。

我建议您将文件作为某种数据结构加载到内存中 - 也许是一组ID。让线程消耗数组中的id。请务必以同步方式访问阵列。

如果文件大于您要加载到内存中的文件或者文件经常被附加到文件中,则创建一个生成器线程,该文件从文件中查看并读取并将ID插入队列类型结构中。

答案 3 :(得分:2)

抱歉,这是工作代码。现在我自己测试一下: - )

package readfilemultithreading;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MultiThreadFileReader
{

    public MultiThreadFileReader(File fileToRead, int numThreads, int numBytesForEachThread)
    {
        this.file = fileToRead;
        this.numThreads = numThreads;
        this.bytesForEachThread = numBytesForEachThread;
        this.bytes = new byte[(int) file.length()];
    }
    private File file;
    private int numThreads;
    private byte[] bytes;
    int bytesForEachThread;

    public byte[] getResult()
    {
        return bytes;
    }

    public void startReading()
    {
        List<ReaderThread> readers = new ArrayList<ReaderThread>();
        for (int i = 0; i < numThreads; i ++) {
            ReaderThread rt = new ReaderThread(i * bytesForEachThread, bytesForEachThread, file);
            readers.add(rt);
            rt.start();
        }
        // Each Thread is Reading....
        int resultIndex = 0;
        for (int i = 0; i < numThreads; i++) {
            ReaderThread thread = readers.get(i);
            while (!thread.done) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                }
            }
            for (int b = 0; b < thread.len; b++, resultIndex++)
            {
                bytes[resultIndex] = thread.rb[b];
            }
        }
    }

    private class ReaderThread extends Thread
    {

        public ReaderThread(int off, int len, File f)
        {
            this.off = off;
            this.len = len;
            this.f = f;
        }
        public int off,  len;
        private File f;
        public byte[] rb;
        public boolean done = false;

        @Override
        public void run()
        {
            done = false;
            rb = readPiece();
            done = true;
        }

        private byte[] readPiece()
        {
            try {
                BufferedInputStream reader = new BufferedInputStream(new FileInputStream(f));
                if (off + len > f.length()) {
                    len = (int) (f.length() - off);
                    if (len < 0)
                    {
                        len = 0;
                    }
                    System.out.println("Correct Length to: " + len);
                }
                if (len == 0)
                {
                    System.out.println("No bytes to read");
                    return new byte[0];
                }
                byte[] b = new byte[len];
                System.out.println("Length: " + len);
                setName("Thread for " + len + " bytes");
                reader.skip(off);
                for (int i = off, index = 0; i < len + off; i++, index++)
                {
                    b[index] = (byte) reader.read();
                }
                reader.close();
                return b;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

以下是使用代码:

package readfilemultithreading;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main
{

    public static void main(String[] args)
    {
        new Main().start(args);
    }

    public void start(String[] args)
    {
        try {
            MultiThreadFileReader reader = new MultiThreadFileReader(new File("C:\\Users\\Martijn\\Documents\\Test.txt"), 4, 2500);
            reader.startReading();
            byte[] result = reader.getResult();
            FileOutputStream stream = new FileOutputStream(new File("C:\\Users\\Martijn\\Documents\\Test_cop.txt"));
            for (byte b : result) {
                System.out.println(b);
                stream.write((int) b);
            }
            stream.close();
        } catch (IOException ex) {
            System.err.println("Reading failed");
        }
    }
}

我现在可以获得+1回复; - )

答案 4 :(得分:0)

您必须以某种方式同步对文件的读取访问权限。我建议使用ExecutorService

您的主线程从文件中读取ID并一次将它们传递给执行程序服务。执行程序将运行N个线程以同时处理N个ID。