Object.notify() will select a random waiting thread and notify that the lock is
released and it can go ahead with obtaining the lock for itself.
Object.notifyAll() will notify all the thread which are waiting for the lock
of that object and they compete over to obtain the lock.
Initially we may think , then if i set varying priorities to each thread then i
can control the sequence. But that not the case , priorities doesn't guarantee
that the higher priority threads will run.
But if you really want to control the sequence of thread execution use
thread synchronizers.
To test that priorities has little say in the Thread selection :
public class NotifyVSNotifyAll {
public static void main(String[] args) {
Object resource = new Object();
Thread a=new Thread(()->{
synchronized (resource) {
System.out.println("A");
try{
Thread.sleep(2000);
resource.notify();
//resource.notifyAll();
}catch(Exception E){}
}
});
Thread b=new Thread(()->{
synchronized (resource) {
System.out.println("B");
}
});
Thread c=new Thread(()->{
synchronized (resource) {
System.out.println("C");
}
});
a.setPriority(10);
b.setPriority(1);
c.setPriority(10);
a.start();
c.start();
b.start();
}
}
Hope its clear.