Monday, August 14, 2023
HomeSoftware DevelopmentThread Lifecycle in Java | Developer.com

Thread Lifecycle in Java | Developer.com


Developer.com content material and product suggestions are editorially impartial. We might make cash once you click on on hyperlinks to our companions. Study Extra.

Threads are basic items of execution in Java that enable for concurrent and parallel execution of duties. Understanding the thread lifecycle is important for writing environment friendly and strong multi-threaded purposes. On this programming tutorial, we’ll dive deep into the assorted phases of the thread lifecycle in Java, accompanied by code examples.

Overview of the Java Thread Lifecycle

There are a number of distinct states concerned within the life cycle of a thread as proven within the following diagram:

Java Thread lifecycle

The remainder of this text will cowl every of the next thread states in additional element:

Learn: Finest On-line Programs to Study Java

Java Thread State: New

At this stage, a thread is created however not but began. You possibly can create a brand new thread by instantiating the Thread class or implementing the Runnable interface and passing it to a Thread occasion like so:

public class NewThreadExample {
  public static void primary(String[] args) {
    Thread newThread = new Thread(() -> {
      System.out.println("New thread is executing.");
    });
    System.out.println("Thread state: " + newThread.getState()); 
    // Output: Thread state: NEW
  }
}

Energetic (Runnable & Operating)

When the begin() methodology known as on a thread, it turns into Energetic by transitioning from the New state to the Runnable state. A thread on this state is eligible to run, however the precise execution will depend on the scheduler. Threads within the Runnable state might be executing concurrently with different threads. Right here is a few instance code:

public class RunnableThreadExample {
  public static void primary(String[] args) {
    Thread runnableThread = new Thread(() -> {
      System.out.println("Runnable thread is executing.");
    });
    runnableThread.begin();
    System.out.println("Thread state: " + runnableThread.getState()); 
    // Output: Thread state: RUNNABLE
  }
}

A thread within the Runnable state can transition to the Operating state when the scheduler allocates processor time to it. The thread’s run() methodology is executed, and it performs its designated duties.

public class RunningThreadExample {
  public static void primary(String[] args) {
    Thread runningThread = new Thread(() -> {
      System.out.println("Operating thread is executing.");
    });
    runningThread.begin();
    // Output: Operating thread is executing.
  }
}

Learn: Prime Java Frameworks

Blocked/Ready

A thread can enter the Blocked or Ready state for varied causes. One widespread situation is when a thread is ready for a lock held by one other thread. A second situation is when a thread is explicitly paused utilizing strategies like Thread.sleep() or Object.wait().

public class BlockedThreadExample {
  public static void primary(String[] args) {
    Object lock = new Object();
    Thread blockedThread = new Thread(() -> {
      synchronized (lock) {
        strive {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    
    Thread waitingThread = new Thread(() -> {
      synchronized (lock) {
        strive {
          lock.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    
    blockedThread.begin();
    waitingThread.begin();
    
    System.out.println("Blocked thread state: " + blockedThread.getState());
    System.out.println("Ready thread state: " + waitingThread.getState());
    /* 
    Output:
    Blocked thread state: TIMED_WAITING
    Ready thread state: BLOCKED
    */
  }
}

Timed Ready

Threads within the Blocked/Ready state can enter the Timed Ready state when they’re paused for a specified period of time. This will occur when utilizing strategies like Thread.sleep() or Object.wait(timeout).

public class TimedWaitingThreadExample {
  public static void primary(String[] args) {
    Thread timedWaitingThread = new Thread(() -> {
      strive {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });
    timedWaitingThread.begin();
    
    System.out.println("Thread state earlier than sleep: " + timedWaitingThread.getState());
    
    strive {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    
    System.out.println("Thread state after sleep: " + timedWaitingThread.getState());
    /* 
    Output:
    Thread state earlier than sleep: RUNNABLE
    Thread state after sleep: TIMED_WAITING
    */
  }
}

Terminated/Useless

A thread enters the Terminated state when its run() methodology completes execution or when an unhandled exception happens. A terminated thread can’t be restarted. You possibly can verify if a thread has terminated utilizing the Thread.isAlive() methodology.

public class TerminatedThreadExample {
  public static void primary(String[] args) {
    Thread terminatedThread = new Thread(() -> {
      System.out.println("Thread is executing.");
    });
    terminatedThread.begin();
    
    strive {
      terminatedThread.be part of();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    
    System.out.println("Is thread terminated? " + !terminatedThread.isAlive());
    /* 
    Output:
    Thread is executing.
    Is thread terminated? true
    */
  }
}

Ultimate Ideas on the Java Thread Lifecycle

On this article, we explored the 5 primary phases of the thread lifecycle: New, Energetic (Runnable/Operating), Blocked/Ready, Timed Ready, and Terminated. Every stage performs a vital function in figuring out how threads work together with one another and with the underlying system sources.

Understanding the thread lifecycle is essential for writing environment friendly and bug-free multi-threaded purposes. Java’s thread administration permits builders to harness the ability of concurrency to construct strong software program programs. By comprehending the assorted phases of the thread lifecycle, builders can create purposes that take full benefit of multi-core processors and supply responsive consumer experiences.

Keep in mind to make use of synchronization mechanisms like synchronized blocks and strategies, in addition to higher-level concurrency utilities supplied by Java’s java.util.concurrent package deal, to make sure correct coordination between threads and stop points like race situations and deadlocks.

By mastering the thread lifecycle and incorporating greatest practices for multi-threaded programming, builders can create Java purposes that excel in efficiency, responsiveness, and scalability.

Subsequent Steps

Now that you’ve a greater understanding of the Java Thread lifecycle and the way the completely different states of the lifecycle function, we suggest you take a look at a few of our different tutorials on Java threading, multithreading, and concurrency. We spotlight a number of under:



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments