我有以下三个课程:
第一类:
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();
}
}
}
}
第 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
}
}
第 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();
}
}
}
First 类是创建线程的主类,它每 5 秒创建两个新线程。
第一个线程 (SendThreadSys1) 将在第二个线程 (ReceivedThreadSys1) 从其开始时间开始每 4 秒后通过将字符串“BYE”发送到标准 i/p 流来停止第二个线程 (ReceivedThreadSys1)。在前 4 秒内,我可以从控制台输入,并且字符串会打印在控制台中。但是在主类中第二次创建新线程后(即 5 秒后),程序没有检测到来自控制台的任何输入。
第二次未检测到来自控制台的任何输入的原因可能是什么?