Hello everyone,


Please look at the following code block,

public void Foo()
{
	synchronized (lock)
	{
		//do task 1
		try {
			lock.wait();
		} catch (InterruptedException e) {
		// TODO Auto-generated catch lock
			e.printStackTrace();
		}
		//do task 2
	}
}

Suppose multiple threads have entered the synchronized block one by one, and then they all release the lock by invoking "wait" on lock object. If sometime later "notifyAll" of the lock object is invoked, all the threads which have been waiting for the lock will be awakened. Then there will be multiple threads executing task 2 (the task just after the wait statement), but task 2 is in a synchronized block, how can multiple threads enter a synchronized block?

Are there anything wrong in my previous statement and the code block?


Thanks in advance,
George

notifyAll() will cause only 1 thread (at most) to start to run.

Thanks jwenting,

notifyAll() will cause only 1 thread (at most) to start to run.

IIRC, notify will wake one thread up, and notifyAll will notify all the threads (waiting for the lock) up. I am wondering why you mean notifyAll() will cause only 1 thread to run?


regards,
George

notifyAll will put all waiting threads in runnable mode, notify just one.
The thread scheduler then picks one thread from the pool of runnable threads (which may or may not be one of the threads woken up by notify(all) as the next thread to run.

You see, notify(all) doesn't actually make the thread run, it just makes sure it CAN run.

Thanks jwenting,

notifyAll will put all waiting threads in runnable mode, notify just one.
The thread scheduler then picks one thread from the pool of runnable threads (which may or may not be one of the threads woken up by notify(all) as the next thread to run.

You see, notify(all) doesn't actually make the thread run, it just makes sure it CAN run.

Your reply is very helpful.


regards,
George

Thanks for all the people who helped me on this thread.


regards,
George

NotfyAll will wake up all the threads(say A and B) and make them runnable, one (say A) will selected by the scheduler to run. As A continues after the wait() call the lock is re-acquired. If a context switch happens and B starts now, it also try to re-acquire the lock. But as it is already locked by A it has to wait till A is finished with his job. So the action in synchronized block is still atomic.

commented: 6 years too late with feeble reply -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.