-1

How can I read a file in Java using multithreading? It doesn't matter if it's slower than using once, I have to do it. So, for example, if there are 2 threads, the first reads the first line and, at the same time, the second reads the second line; then the first reads the third line and the second reads the fourth line and they continue reading in this way since the end of the file. How can I implement this in Java?

Nicola Bernardi
  • 68
  • 1
  • 10
  • 3
    You'd need to set up a sequence, so that the next thread won't start till the last thread has completed, unless your file support random access – MadProgrammer Dec 09 '17 at 21:58
  • And if I use a binary file, so it supports random access? – Nicola Bernardi Dec 09 '17 at 22:04
  • 1
    Then, in theory, you can use `seek` from something like [`RandomAccessFile`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html) to position the read pointer to where ever you want. But, you'll probably find that each `Thread` will need to open the file within it's own context – MadProgrammer Dec 09 '17 at 22:06
  • And there isn't a way to read simultaneously with 2 threads a txt file? – Nicola Bernardi Dec 09 '17 at 22:33
  • Not really, as most input methods are single directional, even if each thread had it's own reader/stream, it'd have to loop over the first `n` lines until it reached the line it wants to read, which is just pointless – MadProgrammer Dec 09 '17 at 22:35
  • looks like a homework – Alexei Kaigorodov Dec 09 '17 at 23:08
  • _Why_ do you need to do it. Can you explain the requirements? So far my guess is a pointless threaded programming assignment where the teacher doesn't get the point of threads. – Gray Dec 10 '17 at 17:30

1 Answers1

1

Just use a single BufferedReader that is shared between the threads, and synchronize on it when calling readLine().

It is completely pointless.

user207421
  • 305,947
  • 44
  • 307
  • 483