1

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • What do you think `n1.isAlive()` does? – Sotirios Delimanolis Jun 29 '17 at 18:46
  • Because the thread is alive for longer? Why do you think the counter shouldn't be higher? – pvg Jun 29 '17 at 18:46
  • .isAlive() checks whether the thread is alive. But why does it die? Not sure about the counter. – Jovan Jovanović Jun 29 '17 at 18:49
  • As the duplicate explains, the `ThreadOne` thread dies when its `run` method returns. In your example, your thread returns when `sleep` exists. So if it sleeps longer, it lives longer. If it lives longer, the `main` thread has more time to loop. – Sotirios Delimanolis Jun 29 '17 at 19:01
  • Thank you. I also appreciate marking the thread as a duplicate. I'm having problems translating all terms from my native language to English, so I didn't know what to search for. – Jovan Jovanović Jun 29 '17 at 19:06

0 Answers0