简体   繁体   English

Java线程-阻止状态

[英]Java Thread - blocked status

I have a very basic question. 我有一个非常基本的问题。 If a thread is busy in IO operation why it is not considered in a RUNNING state? 如果线程在IO操作中处于繁忙状态,为什么不将其视为RUNNING状态? If the IO operation is taking long time it means that the thread is doing its work. 如果IO操作花费很长时间,则意味着该线程正在执行其工作。 How can a thread be called BLOCKED when it is actually doing it's work? 实际工作时如何将其称为“阻塞”?

I don't know where you read that a thread is in the BLOCKED state when doing IO. 我不知道在执行IO时您在何处读取到线程处于BLOCKED状态。 The BLOCKED state documentation says: BLOCKED状态文档说:

Thread state for a thread blocked waiting for a monitor lock. 线程的线程状态被阻塞,等待监视器锁定。 A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait. 处于阻塞状态的线程在调用Object.wait之后正在等待监视器锁定输入同步的块/方法或重新输入同步的块/方法。

So, no, a thread is not in a blocked state while doing IO (unless of course reading or writing forces it to wait on an object's monitor). 因此,不,执行IO时线程不会处于阻塞状态(除非读写会迫使线程在对象的监视器上等待)。

If you run the following code with a thread blocking on IO 如果您在IO上阻塞线程的情况下运行以下代码

public class Main {
    public static void main(String[] args) throws  InterruptedException {
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // blocking read
                try {
                    System.in.read();
                } catch (IOException e) {
                    throw new AssertionError(e);
                }
            }
        });
        thread.start();
        for(int i=0;i<3;i++) {
            System.out.println("Thread status: "+thread.getState());
            Thread.sleep(200);
        }
        System.exit(0);
    }
}

prints 版画

Thread status: RUNNABLE
Thread status: RUNNABLE
Thread status: RUNNABLE

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

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