I have three classes as below:
Class 1:
public class System1Class {
public static void main(String args[]) throws IOException {
while(true) // Every 5 seconds it will create below two new threads.
{
System.out.println("New threads created.");
Thread sndThreadSys1 = new Thread(new SendThreadSys1(), "SendThreadSys1");
Thread rcvThreadSys1 = new Thread(new ReceivedThreadSys1(), "ReceivedThreadSys1");
sndThreadSys1.start();
rcvThreadSys1.start();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Class 2:
public class SendThreadSys1 implements Runnable{
public void run() {
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String st = "BYE";
InputStream is = new ByteArrayInputStream(st.getBytes());
System.setIn(is);
ReceivedThreadSys1.br = new BufferedReader(new InputStreamReader(System.in)); // refresh the br object
}
}
Class 3:
public class ReceivedThreadSys1 implements Runnable{
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void run() {
try{
while(true)
{
while(!br.ready()) // waiting for input from console/Std i/p Stream
{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String s = br.readLine();
System.out.println("Print :::"+s);
if(s.equals("BYE"))
{
break;
}
}
System.out.println("I am outside.");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
The First class is the main class where threads are created and it creates two new threads for every 5 seconds.
The first thread (SendThreadSys1) will stop the second thread (ReceivedThreadSys1) after every 4 seconds from its start time by sending the string "BYE" to Standard i/p stream. In the first 4 seconds I am able type from console and the strings are printed in the console. But after new threads are created for second time in the main class (i.e. after 5 secs), the program is not detecting any input from console.
What could be the reason for not detecting any input from console in the second time?