Threads

 

Life Cycle of A Thread



Different states implementing Multiple-Threads are:




Runnable — waiting for its turn to be picked for execution by the thread schedular based on thread priorities.
Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method:
Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
Blocked on synchronization: Will move to Runnable when a lock is acquired.
Dead: The thread is finished working.


----------------
When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state. In case of sleep acquired resources are released but in case of yield not.
---------------

Daemon threads are sometimes called "service" threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. This thread is provided by the JVM.


Thread Creation

In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:
  • Extending the java.lang.Thread Class
  • Implementing the java.lang.Runnable Interface