wait,notify操作是同一个对象锁,简单例子如下
package com.cienet.wangbin.test;
public class Test7 {
/**
* @param args
*/
public static void main(String[] args) {
new Thread1().start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread2().start();
}
static class Thread1 extends Thread {
@Override
public void run() {
super.run();
int count = 10;
synchronized (Test7.class) {
for (int i = 0; i < count; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 2) {
try {
Test7.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
}
}
}
}
static class Thread2 extends Thread {
@Override
public void run() {
super.run();
int count = 10;
synchronized (Test7.class) {
for (int i = 0; i < count; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 5) {
Test7.class.notify();
}
System.out.println("b" + i);
}
}
}
}
}
如上结果可知,wait是会释放锁的,而notify不会释放锁,当调用它的时候,不能够直接唤醒wait住的线程,而是先等其本身执行完毕后才释放锁。wait住的资源才能获取锁,继续执行。