0

Can anyone explain to me why does this program gives an error when I try to use while instead of if statement inside run() method?

Code not working:

public class threadHello implements Runnable {
    public static int counter = 0;
    Thread t;

    void newThread() {

        t = new Thread(this, "Thread: " + Integer.toString(counter));
        helloWord();
        counter++;
        t.start();

    }

    void helloWord() {
        System.out.println(t.getName() + ": Hello from Thread: " + counter);
    }

    @Override
    public void run() {
        while (counter < 51)
            newThread();

    }
}

Code that works:

public class threadHello implements Runnable {
    public static int counter = 0;
    Thread t;

    void newThread() {

        t = new Thread(this, "Thread: " + Integer.toString(counter));
        helloWord();
        counter++;
        t.start();

    }

    void helloWord() {
        System.out.println(t.getName() + ": Hello from Thread: " + counter);
    }

    @Override
    public void run() {
        if (counter < 51)
            newThread();
    }
}

And when I put the same condition inside my newThread() method program works with both if and while solutions. I would like to understand why?

pirho
  • 11,565
  • 12
  • 43
  • 70
  • 1
    What's the error that you get with while? – SMA Jan 21 '18 at 12:36
  • Here it is: Exception in thread "Thread: 7" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:708) at reversehello.threadHello.newThread(threadHello.java:13) at reversehello.threadHello.run(threadHello.java:23) at java.lang.Thread.run(Thread.java:748) – TutaBugarin Jan 21 '18 at 12:39
  • 1
    That's because you are restarting the same thread again and again in while loop, while with if you are just starting the thread once. You cannot start the same thread multiple times. See the runnable instance that you are passing is the same accross multiple thread instance that you are trying to create. – SMA Jan 21 '18 at 12:44
  • 1
    @SMA I don't think passing the same runnable instance to multiple threads is the issue here. I think that's perfectly fine. For me the problem is a race condition in the assignment of the ``t`` instance field since all loop iterations reuse that same field, then two iterations may end up trying to start the same thread due to race conditions. As a matter of fact if we synchronize the ``newThread`` method the problem is gone, which kind of proves this theory. Although, bottom line, you're right, this is about starting the same thread again, just not for the reasons implied as far as I can tell. – Edwin Dalorzo Jan 21 '18 at 13:05

0 Answers0