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?