Leo
Leo

Reputation: 5235

State of a thread in Java

I got a question like what is the state of a thread when it is created. And the option has both ready and runnable. So my doubts are,

  1. Is there any state called ready state?
  2. If so then, is there any difference between runnable and ready state of a thread?
  3. If so then, what will be the appropiate answer?

Thanks in advance.

Upvotes: 3

Views: 2241

Answers (4)

he meng
he meng

Reputation: 11

you can find answer at VM.java,there are six state

public static Thread.State toThreadState(int threadStatus) {
    if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
        return RUNNABLE;
    } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
        return BLOCKED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
        return WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
        return TIMED_WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
        return TERMINATED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
        return NEW;
    } else {
        return RUNNABLE;
    }
}

Upvotes: 1

Mikhail
Mikhail

Reputation: 4223

Here is java's thread state automat:

enter image description here

Upvotes: 2

TheLostMind
TheLostMind

Reputation: 36304

Actually starting and executing a thread involves collaboration between the JVM and the OS. The JVM makes a call to the underlying OS. The states you mention like ready is the state when the Thread is in the waiting Threads set. This means that the Thread is ready for execution and the Thread scheduler can schedule it.

Don't mix up OS and Java level states. From Java's perspective there are only 5 states

1. New
2. Runnable
3. Waiting
4. Timed Waiting
5. Terminated

Upvotes: 1

Lucas
Lucas

Reputation: 3281

1 - no, it's NEW

2 - NEW is waiting to be executed, RUNNABLE is executing

3 - NEW

Who could answer better than Oracle: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

Upvotes: 2

Related Questions