when I tried to get console input from both main thread and thread I created, the console input can only be retrieved by one thread, either main thread or new thread. code as follow:
public static void main(String[] args)
{
try
{
//start a new thread to accept user input
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
String input = stdIn.readLine();
System.out.println(Thread.currentThread().getName() + ":" + input);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}, "Owen");
thread.start();
//accept user input in main thread
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String input = stdIn.readLine();
System.out.println(Thread.currentThread().getName() + ":" + input);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
possible result is as follow:
always new thread:
main
Owen:main
hello
Owen:hello
what
Owen:what
how could I know current input is going to be retrieved by which thread? or Is there any way to start two consoles(or even more) for each thread?