wait释放锁的说明

wait释放锁的说明

  • wait仅仅释放调用这个对象的锁

wait仅仅释放调用这个对象的锁

package com.hengyunsoft.msg.future;

/**

  • 线程在对象的wait方法上面会释放锁,但是仅仅释放指定对象的锁,比如下面的仅仅释放了锁o2,但是(but)o1锁是没有被释放掉的哦
  • @author pdy

*/
public class Test implements Runnable{

private  Object o1 = new Object();
private Object o2 = new Object();

private void o1l() throws InterruptedException{
	synchronized (o1) {
		o2l();
	}
}

private void o2l() throws InterruptedException {
	synchronized (o2) {
		o2.wait();
	}
}

private void geto2() throws InterruptedException {
	synchronized (o1) {
		System.out.println("o0k");
	}
}



public static void main(String[] args) {
	
	final Test t = new Test();
	
	Thread a = new Thread(t);
	a.setName("只想要取得一把锁的线程");
	Thread b = new Thread(new Runnable() {
		
		@Override
		public void run() {
			try {
				t.o1l();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	});
	b.setName("持有两把锁的线程");
	b.start();
	Thread.yield();
	a.start();
}

@Override
public void run() {

	try {
		geto2();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

}

你可能感兴趣的:(java)