Search code examples
javamultithreadingiobufferedreader

Thread and BufferedReader


I have a problem when I want to use multithreading to act as a Keyboard Listener.

So i write these code.

private static boolean out=false;

public static  void main(String[] args)
{
    new Thread(new Runnable() {
        @Override
        public void run() {
            BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
            try{
                reader.readLine();
                reader.close();
            }catch (Exception e){e.printStackTrace();}
            out=true;
            System.out.println(" have received the keyboard");
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {

            while(true)
                if(out)
                    break;
            System.out.println(" exit the loop");
        }
    }).start();

}

But when I input something in console, it seems that the second Thread can not run.

If my code or expression is unclear or wrong , please tell me.

THANK YOU! `


Solution

  • The 2nd thread is already running as soon as you execute the program but since you have not assigned a new value to your variable out the if-clause will always and infinitly evaluate to false and therefore never break.
    You can fix this by assigning true to out and make it volatile so that alaways the most recent updated value will be used. Try something like this:

    private static volatile boolean out = false;
    
      public static void main( String[] args )
      {
        new Thread( new Runnable()
        {
          @Override
          public void run()
          {
            BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
            try
            {
              reader.readLine();
              // will only be executed after input since BufferedReader.readLine() is blocking.
              out = true;
              reader.close();
            }
            catch ( Exception e )
            {
              e.printStackTrace();
            }
            System.out.println( " have received the keyboard" );
          }
        } ).start();
    
        new Thread( new Runnable()
        {
          @Override
          public void run()
          {
            // added to show that the 2nd thread started.
            System.out.println( "Thread 2 started running...." );
    
            while ( true )
              if ( out )
                break;
            System.out.println( " exit the loop" );
          }
        } ).start();
      }