package com.freeflying.thread.communication;
/**
* Notify不释放锁
* @ClassName: NotifyNotReleaseLock
* @Description:
* @author freeflying
* @date 2018年7月16日
*/
public class NotifyNotReleaseLock {
public static void main(String[] args) {
Object lock=new Object();
NotifyNotReleaseLockA notifyNotReleaseLockA=new NotifyNotReleaseLockA(lock);
notifyNotReleaseLockA.start();
NotifyNotReleaseLockB notifyNotReleaseLockB=new NotifyNotReleaseLockB(lock);
notifyNotReleaseLockB.start();
NotifyNotReleaseLockC notifyNotReleaseLockC=new NotifyNotReleaseLockC(lock);
notifyNotReleaseLockC.start();
}
}
class NotifyNotReleaseLockEx{
public void testMethod(Object lock) {
try {
synchronized (lock) {
System.out.println("begin wait! ThreadName = "+Thread.currentThread().getName());
lock.wait();
System.out.println("end wait! ThreadName = " + Thread.currentThread().getName());
}
} catch (Exception e) {
}
}
public void testNotify(Object lock) {
try {
synchronized (lock) {
System.out.println("begin notify! ThreadName = "+Thread.currentThread().getName()+" time="+System.currentTimeMillis());
lock.notify();
Thread.sleep(5000);
System.out.println("end notify! ThreadName = "+Thread.currentThread().getName()+" time="+System.currentTimeMillis());
}
} catch (Exception e) {
}
}
}
class NotifyNotReleaseLockA extends Thread{
private Object lock;
public NotifyNotReleaseLockA(Object lock) {
this.lock=lock;
}
@Override
public void run() {
NotifyNotReleaseLockEx notifyNotReleaseLockEx=new NotifyNotReleaseLockEx();
notifyNotReleaseLockEx.testMethod(lock);
}
}
class NotifyNotReleaseLockB extends Thread{
private Object lock;
public NotifyNotReleaseLockB(Object lock) {
this.lock=lock;
}
@Override
public void run() {
NotifyNotReleaseLockEx notifyNotReleaseLockEx=new NotifyNotReleaseLockEx();
notifyNotReleaseLockEx.testNotify(lock);
}
}
class NotifyNotReleaseLockC extends Thread{
private Object lock;
public NotifyNotReleaseLockC(Object lock) {
this.lock=lock;
}
@Override
public void run() {
NotifyNotReleaseLockEx notifyNotReleaseLockEx=new NotifyNotReleaseLockEx();
notifyNotReleaseLockEx.testNotify(lock);
}
}
结果:
begin wait! ThreadName = Thread-0
begin notify! ThreadName = Thread-1 time=1531751378724
end notify! ThreadName = Thread-1 time=1531751383724
end wait! ThreadName = Thread-0
begin notify! ThreadName = Thread-2 time=1531751383724
end notify! ThreadName = Thread-2 time=1531751388726
结论:在notify方法调用时,不释放锁,必须执行完synchronized同步方法后才释放锁