Why a thread can only be started once?
If you have tried starting a thread twice either through the same thread instance or Runnable, you must have got an error IllegalThreadStateException, as a thread may not be restarted once it has completed execution according to Java Doc.
Why do we get this IllegalThreadStateException on restarting the thread twice?
This error is thrown to indicate that the thread which you are trying to run/start again is not in an appropriate state for the requested operation.
Program depicting the error condition:
---------------------------------------------------------------------------------------------------------
Or alternatively
So, what if I want to start the thread again?
You can simply start a new instance of the thread. It will work fine.
If you have tried starting a thread twice either through the same thread instance or Runnable, you must have got an error IllegalThreadStateException, as a thread may not be restarted once it has completed execution according to Java Doc.
Why do we get this IllegalThreadStateException on restarting the thread twice?
This error is thrown to indicate that the thread which you are trying to run/start again is not in an appropriate state for the requested operation.
Program depicting the error condition:
package indoscopy; public class StartAgainThread extends Thread{ public void run() { System.out.println("Thread Run Started"); } public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub Thread t1 = new Thread(); t1.start(); t1.start(); }
---------------------------------------------------------------------------------------------------------
Or alternatively
package indoscopy; public class StartAgainThread extends Thread{ public void run() { System.out.println("Thread Run Started"); } public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub Thread t1 = new Thread(); t1.start(); t1.sleep(300); if (!t1.isAlive()) t1.start(); } }
Error which we get on running either of the above programs
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at indoscopy.StartAgainThread.main(StartAgainThread.java:17)
So, what if I want to start the thread again?
You can simply start a new instance of the thread. It will work fine.
No comments:
Post a Comment