When I run:
class ThreadOne extends Thread {
ThreadOne(String name) {
super(name);
start();
}
public void run() {
try {
sleep(1);
} catch (InterruptedException ie) {
}
}
public static void main(String args[]) throws InterruptedException {
ThreadOne n1 = new ThreadOne("Thread 1");
int counter = 0;
while (true) {
if (n1.isAlive() == true) {
counter++;
System.out.println("Thread 1 still running. Counter: " + counter);
} else {
System.out.println("Thread 1 executed");
break;
}
}
}
}
I get result such as:
Thread 1 still running. Counter: 1
Thread 1 still running. Counter: 2
...
Thread 1 still running. Counter: 40
Thread 1 still running. Counter: 41
Thread 1 executed
But when I change the parameter in sleep(), counter increases drastically. This is the example where I've put sleep(5):
Thread 1 still running. Counter: 1
Thread 1 still running. Counter: 2
...
Thread 1 still running. Counter: 154
Thread 1 still running. Counter: 155
Thread 1 executed
What makes this thread stop with execution and why does sleep()
affect the counter?