Thursday, August 17, 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 become profitable if 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 crucial for writing environment friendly and strong multi-threaded functions. On this programming tutorial, we are going to 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’ll be able to 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 & Working)

When the begin() technique 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 is determined by the scheduler. Threads within the Runnable state may 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 Working state when the scheduler allocates processor time to it. The thread’s run() technique is executed, and it performs its designated duties.

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

Learn: High Java Frameworks

Blocked/Ready

A thread can enter the Blocked or Ready state for numerous causes. One frequent 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) {
        attempt {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    
    Thread waitingThread = new Thread(() -> {
      synchronized (lock) {
        attempt {
          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 could occur when utilizing strategies like Thread.sleep() or Object.wait(timeout).

public class TimedWaitingThreadExample {
  public static void primary(String[] args) {
    Thread timedWaitingThread = new Thread(() -> {
      attempt {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });
    timedWaitingThread.begin();
    
    System.out.println("Thread state earlier than sleep: " + timedWaitingThread.getState());
    
    attempt {
      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() technique completes execution or when an unhandled exception happens. A terminated thread can’t be restarted. You’ll be able to examine if a thread has terminated utilizing the Thread.isAlive() technique.

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

Last Ideas on the Java Thread Lifecycle

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

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

Bear 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 bundle, 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 functions that excel in efficiency, responsiveness, and scalability.

Subsequent Steps

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments