[Solved] why thread isnt stopping at count 3?


When the test if (count == 3) is done the value of count is 6.

And your code test it only once.

You need to move the code that is out of the for loop inside it.

You need also to hold a lock on t before call wait. This is done with a synchronized block.

@Override
public void run() {
    int count = 0;
    for (int i = 0; i <= 5; i++) {
        count++;
        System.out.println("counting" + count);

        // Moved block
        if (count == 3) {
            try {
                Thread t = new Thread();
                synchronized (t) {  
                    t.wait(5000);
                }
                System.out.println("thread waiting");
            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        // End of moved block
    }
}

The output will be

counting1
counting2
counting3
thread waiting     // Note: this will be printed after 5 seconds
counting4
counting5
counting6

A similar result, but not identical can be obtained using Thread.sleep, replacing this code

Thread t = new Thread();
synchronized (t) {  
   t.wait(5000);
}

With the following:

Thread.sleep(5000);

A difference between Thread.sleep and Object.wait is that is possible to awake a thread waiting acquiring his lock and calling notify (or notifyAll).

Instead is not possible to awake a thread sleeping with Thread.sleep.

9

solved why thread isnt stopping at count 3?