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 this exception mean?

+3


source to share


6 answers


You are trying to start the thread twice.



+5


source


You cannot start your thread twice.



+1


source


you cannot start your thread twice,

t.start();
t.start();

      

you are trying to run something that is already running, so you get IllegalThreadStateException

0


source


You cannot run the same thread twice.

Create another thread like

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

      

0


source


You only need to start the stream once. You can start the thread again only if the thread is finished.

Below code will not throw any exceptions:

t.start();
if(!t.isAlive()){
   t.start();
 }

      

0


source


Once we started Thread, we were 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

      

0


source







All Articles