notify不釋放鎖

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同步方法後才釋放鎖

發佈了64 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章