Java问题:
退出同步块会自动执行 notifyAll()。这是预期的行为吗?
我已经对其进行了测试,它看起来像 1. 当执行超出同步块时,它会自动 notifyAll() 2. 当方法本身同步时,它会在返回时自动 notify()。(不是 notifyAll())
代码 :
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}));
}
}
}
输出:
[2]:检查锁是否可用...
[2]:获得锁!
[1] : 检查锁是否可用...
[2] : 等待锁..
[1] : 获得锁!!
[1] : 正在等待锁..
MyThread 正在尝试获取锁..
MyThread 已获取锁!
MyThread 正在脱离同步块..
MyThread 已释放锁定!
[1]:收到通知!!!
[1]:我完成了!
[2]:收到通知!!!
[2]:我完成了!