简体   繁体   English

Java - Scanner(System.in)和“阻塞线程”

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

2 basic questions: 2个基本问题:

  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"? 当您使用System.in制作扫描仪,然后编写“scan.nextLine()”时,在点击“输入”之前实际发生了什么? Is the thread running the code sleeping and it is awoken only when a newline character comes in from System.in? 运行代码的线程是否处于休眠状态,只有当换行字符来自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. NEW :尚未启动的线程处于此状态。
  • RUNNABLE : A thread executing in the Java virtual machine is in this state. RUNNABLE :在Java虚拟机中执行的线程处于此状态。
  • BLOCKED : A thread that is blocked waiting for a monitor lock is in this state. BLOCKED :阻塞等待监视器锁定的线程处于此状态。
  • WAITING : A thread that is waiting indefinitely for another thread to perform a particular action is in this state. WAITING :正在等待另一个线程执行特定操作的线程处于此状态。
  • 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. TIMED_WAITING :正在等待另一个线程执行最多指定等待时间的操作的线程处于此状态。
  • TERMINATED : A thread that has exited is in this state. TERMINATED :已退出的线程处于此状态。

The only state where a thread executes any code is the RUNNABLE state. 线程执行任何代码的唯一状态是RUNNABLE状态。

Reading from System.in while there isn't enough data available will put the thread in the BLOCKED state. 在没有足够数据可用时从System.in读取将使线程处于BLOCKED状态。 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. 它将等待更多数据到达,或者InputStream关闭,以先发生者为准(不确定System.in可以关闭,但其他流当然可以),然后再次变为RUNNABLE

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. 从技术上讲,休眠( TIMED_WAITING )和阻塞( BLOCKED )不是相同的状态,但这些状态中的任何一个都会导致线程在继续执行之前等待某事。 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. 不同之处在于BLOCKED线程等待一些I / O操作完成(成功或出错),而TIMED_WAITING线程等待来自JVM中某个其他线程的信号,或者给定的时间过去,以先到者为准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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