Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State of thread while in run() method (Java)

I am trying to understand multithreading in java. As I was going through the various states a Java thread can be in (new, Runnable, Running, Waiting/Blocked, Dead). I tried to run some simple code to check the states of the thread.

I created a class MyThread that extends Thread and overrode run() method.

package com.practice.threads;

public class MyThread extends Thread {

    @Override
    public void run() {
        super.run();
        System.out.println("Running Mythread.");
        System.out.println("State of thread : " + this.getState()); // line 2
    }

}

Now I have created a simple class to test the states of thread :

package com.practice.threads;

public class ThreadStateDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        System.out.println("State of thread : " + myThread.getState());  // line 1
        myThread.start();

    }

}

Running this class give the following output :

State of thread : NEW
Running Mythread.
State of thread : RUNNABLE

The output of line 2 is something I don't understand. When run() method of a thread instance is being executed, how can it be in RUNNABLE state? I saw mention of a RUNNING state in a book (SCJP Suncertified Programmer). Should it not show RUNNING?

like image 595
User3518958 Avatar asked Mar 11 '23 20:03

User3518958


1 Answers

The book has an (easy-to-make) error, the state is RUNNABLE, not RUNNING. There is no RUNNING state, see the JavaDoc:

NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
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.
TERMINATED
A thread that has exited is in this state.

(My emphasis)

It's just an odd, slightly pedantic name, since technically, it's only running if the OS is running it. But it's "running" from the JVM's point of view.

like image 125
T.J. Crowder Avatar answered Mar 20 '23 02:03

T.J. Crowder