-1

I am learning core java and learned about multithreading IllegalStateException.

I have already read standard documentation and this question on SO...but couldn't find proper solution in the context of threads.

In book's words:

IllegalStateException is thrown when you start a thread twice.

I can not understand what it says..even no example is given..

When it occurs in the context of threads? Can anyone give an example?

Community
  • 1
  • 1
Krupal Shah
  • 8,949
  • 11
  • 57
  • 93

2 Answers2

1

Yes, you can't call the start method of the Thread if it's already started.

public void start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws: IllegalThreadStateException - if the thread was already started.

See Also: run(), stop()

(Source)

Eran
  • 387,369
  • 54
  • 702
  • 768
1
   public static void main(String[] args) {
      Thread t = new Thread();
      t.start();
      t.start();
   }

Produces:

Exception in thread "main" java.lang.IllegalThreadStateException    at
java.lang.Thread.start(Thread.java:682)     at
quicktest.CopyOnWrite.main(CopyOnWrite.java:23)
Java Result: 1
markspace
  • 10,621
  • 3
  • 25
  • 39