I am creating threads to read a file in java. When I create 2 threads, each thread reads the whole file while I want them to read different parts of file. I tried putting in sleep(), join(), yield() but after including them it is just slowing down the read.
public class MyClass implements Runnable {
Thread thread;
public MyClass(int numOfThreads) {
for(int i=0;i < numOfThreads; i++) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
readFile();
}
}
In readFile, in the while loop(reading line by line) I invoked the sleep()/yield(). How can I make the threads read different parts of the file?
Updated with method used to read files...
public synchronized void readFile() {
try {
String str;
BufferedReader buf = new BufferedReader(new FileReader("read.txt");
while ((line = buf.readLine()) != null) {
String[] info = str.split(" ");
String first name = info[0];
String second name = info[1];
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
} catch (IOException e) {
System.out.println("Error : File not found");
e.printStackTrace();
}
}
See Question&Answers more detail:os