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.
A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources.
When the method start() is invoked on a thread, the thread scheduler moves that thread to the runnable state. Whenever the join() method is invoked on any thread instance, the current thread executing that statement has to wait for this thread to finish its execution, i.e., move that thread to the terminated state.
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With