participate


New To Java - notify and notifyAll
<<   Back to Forum  |   Give us Feedback
This topic has 3 replies on 1 page.
JoshuaAntony
Posts:314
Registered: 2/11/06
notify and notifyAll   
May 17, 2006 1:47 AM

 
notify results in a single thread acquiring a lock whereas notifyAll results in all the threads competing for the lock and one of them acquiring it
so any way only one thread is able to acquire the lock, so why do we need notfyAll at all.
Is there something more to it.
 
kajbj
Posts:28,276
Registered: 3/21/00
Re: notify and notifyAll   
May 17, 2006 2:07 AM (reply 1 of 3)  (In reply to original post )

 
Yes, there's a good reason to have notifyAll. notify will only wake one thread up, the others will still be waiting for something to happen. notifyAll will wake all threads up so that they know that something has happened (that is all threads will continue to execute when they can acquire the lock)

Kaj
 
kajbj
Posts:28,276
Registered: 3/21/00
Re: notify and notifyAll   
May 17, 2006 2:08 AM (reply 2 of 3)  (In reply to #1 )

 
It can all be illustrated by an example:

public class Test {
 
	public static void main(String[] args) throws Exception {
		final Object lock = new Object();
		
		class R implements Runnable {
			public void run() {
				synchronized (lock) {
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.err.println("Thread " + toString() + " ended");
			}
		}
		
		synchronized (lock) {
			new Thread(new R()).start();
			new Thread(new R()).start();
			new Thread(new R()).start();
		}
		Thread.sleep(1000);
		synchronized (lock) {
			lock.notify();	//Change this line to notifyAll
		}			
		System.out.println("Main thread ended");
	}
}


Kaj
 
BIJ001
Posts:6,897
Registered: 2003.06.06.
Re: notify and notifyAll   
May 17, 2006 2:20 AM (reply 3 of 3)  (In reply to original post )

 
There is a difference whether all waiting threads are waken and compete for the lock or only one. Only one is able to acquire the lock at a given moment, but later on the two scenarios differ.
 
This topic has 3 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 27
  • Guests : 138

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums