NOTE: Donít Ask for How To Compile, where to place the files , where to keep txt files etc.
First Thread Class File (FirstThread.java)
import java.io.*;
import java.util.Random;
public class FirstThread extends Thread {
String fileName;
public FirstThread(String fileName) {
this.fileName = fileName;
}
public void run() {
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = "";
line = br.readLine();
Random rand = new Random();
while (line != null) {
System.out.println("Read Message from first file
"+line);
sleep(rand.nextInt(1000 - (1 + 1) + 1));
line = br.readLine();
}
fr.close();
br.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Second Thread Class File (SecondThread.java)
import java.io.*;
import java.util.Random;
public class SecondThread extends Thread {
String fileName;
public SecondThread(String fileName) {
this.fileName = fileName;
}
public void run() {
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = "";
line = br.readLine();
Random rand = new Random();
while (line != null) {
System.out.println("Read Message from second file
"+line);
sleep(rand.nextInt(1000 - (1 + 1) + 1));
line = br.readLine();
}
fr.close();
br.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Main File (MainThread.java)
public class MainThread {
FirstThread first = new FirstThread("d://first.txt");
Thread t1 = new Thread(first);
SecondThread second = new SecondThread("d://second.txt");
Thread t2 = new Thread(second);
public MainThread() {
t1.start();
t2.start();
}
public static void main(String args[]) {
MainThread m = new MainThread();
}
}
first.txt file (as per my code place this file on root of D Drive or change path in code)
1
2
3
4
5
6
7
8
9
second.txt file (as per my code place this file on root of D Drive or change path in code)
21
22
23
24
25
26
27
28
29
30
Output

Sponsored Links