I am trying to develop a java program containing two threads that reads two files simultaneously.
In a program, first thread reads data from file “Personal_Record.txt” and second thread reads the data from file “Academic_Record.txt”.
When one thread reads a line from one file then it should allow another thread to read a line from another file.
After reading data from each file, program must write the output on console (Output screen) such that one line from first input file is printed and then one line from another input file is printed and so on.
Here are sample files
First File Name: "Personal_Record.txt"
STD01 Saqib 18
STD02 Kashif 17
STD03 Memoona 19
STD04 Madiha 18
STD05 Sidra 18
STD06 Hina 17
STD07 Shahid 19
STD08 Huma 18
STD09 Saeeda 17
STD10 Anjum 18
Second File Name: "Academic_Record.txt"
BCS 3.4
BCS 3.5
MCS 2.6
BIT 3.0
BBA 2.7
BCS 3.0
MIT 3.2
BIT 3.4
BBA 3.2
BCS 2.9
Sample Output
STD01 Saqib 18
BCS 3.4
STD02 Kashif 17
BCS 3.5
STD03 Memoona 19
MCS 2.6
STD04 Madiha 18
BIT 3.0
STD05 Sidra 18
BBA 2.7
STD06 Hina 17
MIT 3.2
STD07 Shahid 19
BCS 3.0
STD08 Huma 18
BIT 3.4
STD09 Saeeda 17
BBA 3.2
STD10 Anjum 18
BCS 2.9
import java.io.*;
public class ReadingFileMT implements Runnable{
//attribute used for name of file
String fileName;
ReadingFileMT(String fn){
this.fileName = fn;
}
// overriding run method
// this method contains the code for file reading
public void run (){
try{
// connecting FileReader with attribute fileName
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = "";
// reading line by line data from file
// and displaying it on console
line = br.readLine();
while (line!=null){
System.out.println(line);
Thread.sleep(1000);
line = br.readLine();
}
fr.close();
br.close();
}
catch (Exception e){
System.out.println(e);
}
} // end run() method
}
public class ThreadFile {
public static void main(String[] args) {
//Creating ReadFileMT object passing file names to them;
ReadingFileMT personalRecord = new ReadingFileMT("Personal_Record.txt");
ReadingFileMT academicRecord = new ReadingFileMT("Academic_Record.txt");
Thread firstFile = new Thread(personalRecord);
Thread secondFile = new Thread(academicRecord);
//Starting Threads
firstFile.start();
//Thread.State.WAITING.wait();
secondFile.start();
try {
//while(firstFile.isAlive()){
firstFile.join(1000);
//}
}catch (Exception ex) {
System.out.println(ex);
}
}
}
But I not produce same Output as I mention. Please help me in this regard to solve this problem