Tuesday, 3 June 2014

Thread Life Cycle in Java and the Difference Between wait() and sleep() Methods

First, let's understand the concepts of Process and Thread. Once we have a clear understanding of these concepts, we can discuss the Thread Life Cycle in Java.

Process:--
         An executing instance of a program is called a process. Each process has its own address space (memory space) and can contain one or more threads.

Example:

If you open multiple instances of a Calculator application, each running instance is considered a separate process. Each process has its own memory and resources allocated by the operating system.


Thread:--
  
Threading is a mechanism that allows multiple tasks or activities to execute concurrently within a single process. Most modern operating systems support multithreading, and the concept of threads has existed in various forms for many years. Java was one of the first mainstream programming languages to provide built-in support for multithreading, rather than relying solely on the underlying operating system.

Threads are often referred to as lightweight processes. Similar to processes, threads represent independent paths of execution within a program. Each thread has its own stack, program counter, and local variables. However, unlike separate processes, threads within the same process share resources such as memory, file handles, and other process-level data.

        Because threads share the same memory space, communication between them is more efficient than communication between separate processes. However, this shared access also introduces challenges such as synchronization and thread safety, which must be handled carefully.



Thread Life Cycle:-

A thread can be in one of the following states ,
  1. New born state(New)
  2. Ready to run state (Runnable)
  3. Running state(Running)
  4. Blocked state
  5. Dead state

Thread Life Cycle
Thread Life Cycle In Java


New Born State:--

  • A thread enters the New (Newborn) state as soon as it is created using the new operator.

  • From the New state, the thread can transition to either the Runnable (Ready-to-Run) state or the Dead (Terminated) state.
  • When the start() method is called, the thread moves to the Runnable state, where it becomes eligible for execution by the thread scheduler.

  • If the thread is terminated before execution, it enters the Dead state.

Note: The stop() method has been deprecated and should not be used in modern Java applications because it can leave shared resources in an inconsistent state.



Ready to run mode (Runnable Mode):--
  • If the thread is ready for execution but waiting for the CPU the thread is said to be in ready to run mode. 
  • All the events that are waiting for the processor are queued up in the ready to run mode and are served in FIFO manner or priority scheduling.
  • From this state the thread can go to running state if the processor is available using the scheduled( ) method. 
  • From the running mode the thread can again join the queue of runnable threads. 
  • The process of allotting time for the threads is called time slicing.


Running State:--

  • If a thread is currently being executed by the CPU, it is said to be in the Running state.

  • A thread may complete its task and terminate normally after finishing its execution.
  • A running thread may also be forced to relinquish control and move out of the Running state when one of the following conditions occurs:

  1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by using the resume() method.
  2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method. The sleeping method re-enters runnable state when the time elapses.
  3.  A thread can be made to wait until a particular event occur using the wait() method, which can be run again using the notify( ) method.

Blocked State:--
  • A thread is said to be in blocked state if it prevented from entering into the runnable state and so the running state.
  • The thread enters the blocked state when it is suspended, made to sleep or wait. 
  • A blocked thread can enter into runnable state at any time and can resume execution.
Dead State:--
  • The running thread ends its life when it has completed executing the run() method which is called natural dead. 
  • The thread can also be killed at any stage by using the stop( ) method.


Difference between wait() and sleep() methods in Java:
  1. The wait() method can be called only from a synchronized context (a synchronized method or block), whereas the sleep() method can be called from any context and does not require synchronization.

  2. The wait() method is defined in the Object class and is called on an object, whereas the sleep() method is defined in the Thread class and is called on a thread.

  3. A thread that is waiting using wait() can be awakened by another thread using the notify() or notifyAll() methods. In contrast, a sleeping thread cannot be awakened using notify() or notifyAll(); it wakes up only after the specified sleep time expires or if it is interrupted.

  4. The wait() method is typically used for inter-thread communication, where a thread waits until a specific condition becomes true. The sleep() method is used simply to pause the execution of the current thread for a specified period.

  5. When a thread calls wait(), it releases the lock (monitor) on the object and enters the waiting state. However, when a thread calls sleep(), it does not release any locks it holds during the sleep period.


Related Post:-
Thread(or Multithread) interview questions & answers 

No comments:

Post a Comment