Sunday, 13 September 2015

Why can't a Java Thread object be restarted?

It's arguably much easier to reason about (and probably implement) a Thread that simply executes its given task exactly once and is then permanently finished. To restart threads would require a more complex view on what state a program was in at a given time.

So unless you can come up with a specific reason why restarting a given Thread is a better option than just creating a new one with the same Runnable.

class ThreadExample {
    public static void main(String[] args){
           Thread myThread = new Thread() {
                  public void run() {
                        for(int i=0; i<3; i++) {
                               try {
                                      sleep(100);
                               } catch(InterruptedException ie) {
                               }
                               System.out.print(i+", ");
                        }
                        System.out.println("done.");
                  }
           };

           myThread.start();

           try {
                  Thread.sleep(500);
           } catch(InterruptedException ie) {
           }
           System.out.println("Now myThread.run() should be done.");
           // <-- causes java.lang.IllegalThreadStateException
           myThread.start();
    }
}

Output:
0, 1, 2, done.
Now myThread.run() should be done.
Exception in thread "main" java.lang.IllegalThreadStateException
   at java.lang.Thread.start(Unknown Source)
    at com.threads.status.ThreadExample.main(ThreadExample.java:30)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...