-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,499
  • 11
  • 56
  • 91

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
  • 374,785
  • 51
  • 663
  • 734
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
  • 9,890
  • 2
  • 22
  • 37