最简略的wait和notify例子

最简单的wait和notify例子
1.前言
网上很多例子都有点问题,会抛监视的异常,原因大多都是没有权限获取锁的问题,需要注意的是wait和notify都要放在synchronized代码块里面,synchronized (obj)中的obj就是锁。
2.代码.
public class Test2 extends Thread {
	public static Object obj = new Object();
	public static Integer signal = new Integer(1);

	@Override
	public void run() {
			System.out.println("aa");
			try {
				Thread.sleep(500);
				synchronized (obj) {
					obj.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("bb");
	}
	public void wakeUp(){
		synchronized (obj) {
			obj.notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		Test2 test2 = new Test2();
		new Thread(test2).start();
		Thread.sleep(9000);
		test2.wakeUp();
	}

}

1 楼 opnmzxcvb 16 小时前  
this.notify();
this.notifyAll();
不需要放在synchronized代码块里面,要注意!!!!