Sincronização Java está fazendo auto notificação na saída? Isso é esperado?
Pergunta Java:
Sair do bloco de sincronização automaticamente faz notifyAll (). Esse é o comportamento esperado?
Eu testei e parece que 1. quando uma execução sai do bloco de sincronização, ele auto notifyAll () 2. Quando o próprio método é sincronizado, ele auto notificará () quando ele retornar (not notifyAll ()).
Código:
<pre><code>public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread lock = new MyThread();
new WatingThread(lock,1).start();
new WatingThread(lock,2).start();
//above tow threads would start and then wait for a lock
lock.start();
}
}
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("MyThread is trying to acquire the lock ..");
synchronized (this) {
System.out.println("MyThread has acquired the lock !!");
System.out.println("MyThread is Coming out of synch block..");
}
System.out.println("MyThread has released the lock !!");
}
}
class WatingThread extends Thread
{
private Object lock;
private int id;
public WatingThread(Object lock, int id )
{
this.lock = lock;
this.id = id;
}
@Override
public void run() {
System.out.println(String.format("[%d] : Check if lock is available ...",new Object[]{id}));
synchronized (lock) {
System.out.println(String.format("[%d] : Acquired the lock !!",new Object[]{id}));
try {
System.out.println(String.format("[%d] : Going to wait on lock.. ",new Object[]{id}));
lock.wait();
System.out.println(String.format("[%d] : Got notified !!!",new Object[]{id}));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("[%d] :I am done !!",new Object[]{id}));
}
}
}
</code></pre>
Saída:
[2]: verificar se o bloqueio está disponível ...
[2]: Adquiriu a fechadura !!
[1]: verificar se o bloqueio está disponível ...
[2]: indo esperar no bloqueio ..
[1]: Adquiriu a fechadura !!
[1]: indo esperar na fechadura ..
MyThread está tentando adquirir o bloqueio ..
MyThread adquiriu o bloqueio !!
MyThread está saindo do bloco de sincronização.
MyThread liberou o bloqueio !!
[1]: fui notificado !!!
[1]: Eu terminei !!
[2]: fui notificado !!!
[2]: Eu terminei !!