2

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?

Owen Lee
  • 21
  • 2
  • Did you find any solution for this problem? I have the same issue, trying to send a user input to a specific thread or if this is not possible handle a single user input by multipe threads – user35934 Jul 29 '18 at 13:46

0 Answers0