像read()这样的I/O方法如何在Java中将线程置于阻塞状态? [英] How does I/O-methods like read() put a Thread in blocked state in java?

查看:153
本文介绍了像read()这样的I/O方法如何在Java中将线程置于阻塞状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果我正确理解了这一点,则当我们在对象上调用wait时,线程将进入等待状态,而在等待对象上的锁时,线程将进入阻塞状态(例如,尝试进入同步状态时)块或方法).

So, if i have understood this correctly, a thread goes into waiting state when we call wait on an object and it goes into blocked state when it is waiting for a lock on an object(like when trying to get into a synchronized block or method).

但是类似read()的I/O方法如何将线程置于阻塞状态?我知道为什么它必须处于阻塞状态,等待它可以读取的数据,但我也对HOW感兴趣.当试图读取的资源中的数据再次可用时,JVM如何通知线程可以继续执行?

How does I/O-methods like read() put a Thread in a blocked state though? I understand WHY it has to be in a blocked state, waiting for data that it can read but i'm also interested in HOW. How does the JVM notify the thread that it can continue when data in the resource its trying to read, is available again?

推荐答案

它不会将线程的状态更改为BLOCKED

It doesn't change the state of the thread to BLOCKED

public static void main(String[] args) throws IOException {
    Thread main = Thread.currentThread();
    new Thread(() -> {
        for (int i = 0; i < 10; i++) {
            System.out.println(main + " is in "+main.getState()+" state");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new AssertionError(e);
            }
        }
    }).start();
    System.in.read();
}

打印

Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state
Thread[main,5,main] is in RUNNABLE state

相反,直到有一些数据并且操作系统决定是否以及何时上下文切换线程/进程时,操作系统才从read返回.

instead the OS doesn't return from the read until there is some data and the OS decides whether and when to context switch the thread/process.

当尝试读取的资源中的数据再次可用时,JVM如何通知线程可以继续执行线程?

How does the JVM notify the thread that it can continue when data in the resource its trying to read, is available again?

当有更多数据或流已关闭时,操作系统将唤醒线程. JVM不参与.

The OS wakes the thread when there is more data or the stream has been closed. The JVM doesn't get involved.

这篇关于像read()这样的I/O方法如何在Java中将线程置于阻塞状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆