【发布时间】:2013-06-06 06:22:16
【问题描述】:
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]:我完成了!
【问题讨论】:
-
上述代码的输出是:
-
输出是:输出:
[2]:检查锁是否可用...
[2]:获得锁!
[1] : 检查锁是否可用 ...
[2] : 正在等待锁..
[1] : 获得了锁 !!
[1] : Going to wait on lock..
MyThread 正在尝试获取锁..
MyThread 已获取锁!
MyThread 正在退出同步块..
MyThread 已释放锁!
[1]:收到通知!!!
[1]:我完成了!
[2]:收到通知!!!
[2]:我完成了!
标签: java