Ad

Sunday 13 July 2014

java.lang.IllegalThreadStateException at java.lang.Thread.start

IllegalThreadStateException is thrown when you try to start the thread more than once on the same thread object instance.Start method can be invoked only when the Current thread state is "New".For other states like Runnable,Running  or waiting etc invoking start method will throw the IllegalThreadStateException.

Below sample will show the typical scenario where the IllegalThreadStateException will be thrown:

public class IllegalThreadStateSample {                                                                                                    

public static void main(String[] args) {
        ProcessThread processThread= new ProcessThread();
        Thread thread= new Thread(processThread,"ProcessThread");
        thread.start();//ProcessThread State will become "Runnable" and then "Running"
        thread.start();//Starting the ProcessThread for the second time
}

}

class ProcessThread implements  Runnable {

public void run() {
System.out.println("Thread started::"+Thread.currentThread().getName());
}
}

When we run this program,IllegalThreadStateException  will be thrown as shown below:

Thread started::ProcessThread                                                                                                                  
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at test.IllegalThreadStateSample.main(IllegalThreadStateSample.java:9)

  • When we create the thread object(i.e new Thread(processThread,"ProcessThread")),the State of the ProcessThread will be become "New".
  • Invoking the start method will make the state of the Processthread to "Runnable" or "Running" and the ProcessThread started its execution.
  • Since Start method is invoked on the same thread object for the second time whose state is not "New",IllegalThreadStateException is thrown

2 comments:

  1. ...very good!
    ThankyouMyFriend!!!

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Online Java Training Online Java Training

    ReplyDelete