Java Thread - blocked status

后端 未结 2 873
无人共我
无人共我 2020-12-19 05:58

I have a very basic question. If a thread is busy in IO operation why it is not considered in a RUNNING state? If the IO operation is taking long time it means that the thre

2条回答
  •  执念已碎
    2020-12-19 06:44

    If you run the following code with a thread blocking on 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
    

提交回复
热议问题