简体   繁体   中英

Java - Scanner(System.in) and “Blocking a thread”

2 basic questions:

  1. When you make a scanner out of System.in, and then you write, say, "scan.nextLine()", what is actually happening before you hit "enter"? Is the thread running the code sleeping and it is awoken only when a newline character comes in from System.in? How else would it wait for the human to type in the input?

  2. When a thread is "blocked" does that mean that it's asleep? Or does it just mean that it can't enter a certain piece of code, but could be doing other stuff?

At any point in time, every thread is in one thread state. The possible thread states are

  • NEW : A thread that has not yet started is in this state.
  • RUNNABLE : A thread executing in the Java virtual machine is in this state.
  • BLOCKED : A thread that is blocked waiting for a monitor lock is in this state.
  • WAITING : A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • TIMED_WAITING : A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  • TERMINATED : A thread that has exited is in this state.

The only state where a thread executes any code is the RUNNABLE state.

Reading from System.in while there isn't enough data available will put the thread in the BLOCKED state. There it will wait for more data to arrive, or the InputStream to close, whichever happens first (not sure if System.in can be closed, but other streams certainly can), and then become RUNNABLE again.

Technically speaking, sleeping ( TIMED_WAITING ) and blocking ( BLOCKED ) are not the same states, but either of these states will cause the thread to wait for something before continuing execution. The difference is that BLOCKED threads wait some I/O operation to complete (successfully or with an error), whereas TIMED_WAITING threads wait for a signal from some other thread in the JVM, or a given amout of time to elapse, whichever comes first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM