Java - Scanner (System.in) and "Blocking Thread"
2 main questions:
-
When you make a scanner from System.in and then write, say, "scan.nextLine ()", what actually happens before you hit enter? Is the thread running the code asleep and only wakes up when a newline appears in System.in? How else will it wait for human input?
-
When a thread is blocked, does that mean it is sleeping? Or does it just mean that it cannot enter a certain piece of code, but can it do other things?
source to share
At any given time, each thread is in the same thread state. Possible thread states :
-
NEW
: A thread that has not yet started is in this state. -
RUNNABLE
: A thread running in the Java Virtual Machine is in this state. -
BLOCKED
: A thread blocked waiting for a monitor lock is in this state. -
WAITING
: A thread that is waiting indefinitely for another thread to perform a certain action is in this state. -
TIMED_WAITING
: A thread is in this state, waiting for another thread to perform an action before the specified timeout. -
TERMINATED
: The exit from this thread is in this state.
The only state in which a thread executes any code is state RUNNABLE
.
Reading from System.in
while there is not enough data, the stream will be put into state BLOCKED
. There it will wait for more data or closure InputStream
, whichever comes first (not sure if System.in
it can be closed, but possibly other threads), and then it will again RUNNABLE
.
Technically, 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. The difference is that threads BLOCKED
wait for some I / O operation (success or failure), while TIMED_WAITING
threads wait for a signal from some other thread in the JVM or for a given time, whichever comes first.
source to share