Reputation: 1719
In Java, I am getting this Exception:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at Threads4.go(Threads4.java:14)
at Threads4.main(Threads4.java:4)
Here is the code:
public class Threads4 {
public static void main(String[] args){
new Threads4().go();
}
void go(){
Runnable r = new Runnable(){
public void run(){
System.out.println("foo");
}
};
Thread t = new Thread(r);
t.start();
t.start();
}
}
What does the exception mean?
Upvotes: 4
Views: 10410
Reputation: 57
Once we started a Thread we are not allowed to restart the same Thread otherwise we will get IllegalThreadStateException
in your code just remove the line
Thread t = new Thread(r);
t.start();
t.start(); // Remove this line
Upvotes: 0
Reputation: 7890
you cannot start your thread twice,
t.start();
t.start();
you are trying to start something which is already started, so you getting IllegalThreadStateException
Upvotes: 0
Reputation: 10677
You should start the thread only once. You can start a thread again only if thread has completed running.
Below code will not throw any exception:
t.start();
if(!t.isAlive()){
t.start();
}
Upvotes: 0
Reputation: 15729
You can't start the same Thread twice.
Create another Thread, e.g.
Thread thread2 = new Thread(r);
thread2.start();
Upvotes: 0