java.lang.IllegalThreadStateException while starting the thread twice in java


In this Example we are going to understanding the exception when we start a thread twice.

Error Message :
Thread started and running
Exception in thread "main" java.lang.IllegalThreadStateException
       at java.base/java.lang.Thread.start(Thread.java:795)
       at com.si.exceptions.IllegalThreadStateException.m1(IllegalThreadStateException.java:14)
       at com.si.exceptions.IllegalThreadStateException.main(IllegalThreadStateException.java:8)

Error Description :

package com.si.exceptions;

public class IllegalThreadStateException extends Thread{

       public static void main(String[] args) {
              IllegalThreadStateException t1 = new IllegalThreadStateException();
              t1.start();
              m1(t1);
             
       }

       private static void m1(Thread t) {
              System.out.println("Thread started and running");
               t.start();
       }

      
}
      
      
In the above example ,the red background color line is giving the exception.
We Start a thread in yellow coded line ,so now thread state is NEW. Now we are starting again the same thread in red coded line.so we are starting the thread twice. That's why we are getting the IllegalThreadStateException.

Solution:


To avoid this exception We need to check the status of the current thread.if the state is not new then we do not start again as shown in green color code.


package com.si.exceptions;

public class IllegalThreadStateException extends Thread{
        public enum State {
               NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
           }
       public static void main(String[] args) {
              IllegalThreadStateException t1 = new IllegalThreadStateException();
              t1.start();
              m1(t1);
             
       }

       private static void m1(Thread t) {
              System.out.println("Thread started and running");
             
               if(Thread.State.NEW==null) {
                      t.start();
               }else {
                      System.out.println("doing thread manipulations");
                    
               }
       }

      
}

Output:
Thread started and running
doing thread manipulations
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar