10

I want to know how and when does a Thread move back and forth between runnable and running states.What actually happens behind the scenes.I guess this will be needed in case of ThreadPool but I am not able to understand entirely.Please help me to understand this.

Bhavya Sharma
  • 309
  • 3
  • 15
  • 1
    Why do you need to know? I don't know this either, but have successfully used `ThreadPool` without such knowledge. – Andy Turner Jan 20 '16 at 04:49
  • I was just wondering.....if thread is in running state that means its executing run() method and when its in runnable method its executing start() method....so I guess moving from running to runnable means its going back from run() to start()....please correct me if I am wrong as I am a beginner to multithreading – Bhavya Sharma Jan 20 '16 at 04:53
  • Thread scheduling is an implementation detail of the particular JVM. The best advice is to design your code to NOT depend on scheduling tricks, priority tweaks, or thread.yield() since such code will not be portable. Let the JVM attend to thread scheduling. In the best case, most of the time you shouldn't need to be aware of it. – scottb Jan 20 '16 at 05:00
  • In this question are you referring to `Thread.State`(https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.State.html)? The closest state I see here are `NEW` and `RUNNABLE`, and the documentation says that a thread changes from the former when it is started. – FThompson Jan 20 '16 at 05:04
  • @scottb..thanks for the answer.....just tell me one thing moving back to runnable from running means thread is moving back from run() method to start()...do correct me if I am wrong – Bhavya Sharma Jan 20 '16 at 05:05
  • @Vulcan....I have read in so many docs that threascheduler might change thread state from running to runnable back and forth but I am not able to find any explanation for this. – Bhavya Sharma Jan 20 '16 at 05:08
  • http://www.journaldev.com/1044/life-cycle-of-thread-understanding-thread-states-in-java – Venkat Jan 20 '16 at 05:16
  • @BhavyaSharma Could you include relevant documentation in the question please? So your readers have a common baseline understanding of what specifically you're asking about. – FThompson Jan 20 '16 at 05:18
  • @Vulcan.......kindly read last sentence http://www.bogotobogo.com/Java/tutorial/threads.php – Bhavya Sharma Jan 20 '16 at 05:25
  • See also http://stackoverflow.com/questions/15841301/difference-between-running-and-starting-a-thread – Raedwald Jan 20 '16 at 14:30
  • There is no "RUNNING" state in Thread.State. – Leon May 26 '19 at 05:54

3 Answers3

10

if thread is in running state that means its executing run() method and when its in runnable method its executing start() method....so I guess moving from running to runnable means its going back from run() to start()

In the nomenclature of most operating systems, "running" means that the thread actually is executing instructions on some CPU, and "runnable" means that nothing prevents the thread from "running" except the availability of a CPU to run on.

A Java program can not tell the difference between those two states. The thread states that Java knows about are NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.

A thread is NEW before t.start() is called, and it can never go back to NEW afterward. WAITING and TIMED_WAITING both mean that the thread is waiting for a notify() call in some other thread. BLOCKED means it is waiting for anything else (e.g., to enter a synchronized block), and TERMINATED means it's finished.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
1

Yield is a static method that tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.

There is no guarantee that Yield will make the currently executing thread to runnable state immediately. Remember an important point that yield method does not make the thread to go to Wait or Blocked state. It can only make a thread from Running State to Runnable State.

marcospereira
  • 12,045
  • 3
  • 46
  • 52
Anand Pandey
  • 383
  • 4
  • 12
  • `yield()` is rarely called, and it is certainly not the major mechanism at work here. Don't use code formatting for text that isn't code. – user207421 Jan 20 '16 at 05:10
  • @Anand.....thanks for the explanation.Just one more doubt....we will use yield manually in our code...right? How does JVM take care of this on its own? – Bhavya Sharma Jan 20 '16 at 05:12
  • *"There is no guarantee that Yield will make the currently executing thread to runnable state immediately."* ... Indeed. It would be perfectly acceptable for a JVM to do absolutely nothing at all when Thread.yield() is invoked. A program that depends upon the behavior of Thread.yield() for its correctness is a non-portable program at best, and a deeply flawed program at worst. – scottb Jan 20 '16 at 05:13
0

Extract from A Programmer's Guide to Java SCJP Certification: Threads:

static void yield() This method causes the current thread to temporarily pause its execution and, thereby, allow other threads to execute. It is up to the JVM to decide if and when this transition will take place.

static void sleep (long millisec) throws InterruptedException The current thread sleeps for the specified time before it becomes eligible for running again.

final void join() throws InterruptedException final void join(long millisec) throws InterruptedException A call to any of these two methods invoked on a thread will wait and not return until either the thread has completed or it is timed out after the specified time, respectively.

void interrupt() The method interrupts the thread on which it is invoked. In the Waiting-for-notification, Sleeping, or Blocked-for-join-completion states, the thread will receive an InterruptedException.

Below Example illustrates transitions between thread states. A thread at (1) sleeps a little at (2) and then does some computation in a loop at (3), after which the thread terminates. The main() method monitors the thread in a loop at (4), printing the thread state returned by the getState() method. The output shows that the thread goes through the RUNNABLE state when the run() method starts to execute and then transits to the TIMED_WAITING state to sleep. On waking up, it computes the loop in the RUNNABLE state, and transits to the TERMINATED state when the run() method finishes.

Example :Thread States

public class ThreadStates {

  private static Thread t1 = new Thread("T1") {    // (1)
    public void run() {
      try {
        sleep(2);                                  // (2)
        for(int i = 10000; i > 0; i--);            // (3)
      } catch (InterruptedException ie){
        ie.printStackTrace();
      }
    }
  };

  public static void main(String[] args) {
    t1.start();
    while(true) {                                  // (4)
      Thread.State state = t1.getState();
      System.out.println(state);
      if (state == Thread.State.TERMINATED) break;
    }
  }
}

Possible output from the program:

RUNNABLE
TIMED_WAITING
...
TIMED_WAITING
RUNNABLE
...
RUNNABLE
TERMINATED
Nargis
  • 4,687
  • 1
  • 28
  • 45