Abhijeet
Abhijeet

Reputation: 1719

Java Exception java.lang.IllegalThreadStateException

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

Answers (6)

Mohammad Shamshuddeen
Mohammad Shamshuddeen

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

exexzian
exexzian

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

rai.skumar
rai.skumar

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

user949300
user949300

Reputation: 15729

You can't start the same Thread twice.

Create another Thread, e.g.

Thread thread2 = new Thread(r);
thread2.start();

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117645

You cannot start your thread twice.

Upvotes: 1

Jeff Storey
Jeff Storey

Reputation: 57202

You're trying to start the thread twice.

Upvotes: 6

Related Questions