结论:
1.synchronized (lockObj),lockObj.wait()和lockObj.notify()的锁对象要统一,且wait()和notify()应该在synchronized{}块内使用
2.wait()方法让持有锁的线程进入阻塞并进入等待池,同时释放锁
3.lockObj.notify()方法在synchronized (lockObj){}同步块运行完之后,会去lockObj的等待池中唤醒某一等待线程来重新竞争lockObj锁对象
示例:
@Override
public void run() {
if (Thread.currentThread().getName().contains("0")) {
synchronized (lockObj) {
//线程0阻塞进入lockObj的等待池中,并释放lockObj
lockObj.wait();
}
}
if (Thread.currentThread().getName().contains("1")) {
//线程1持有lockObj
synchronized (lockObj) {
//线程1持有另一把锁otherLockObj
synchronized (otherLockObj) {
//此时线程0被唤醒
lockObj.notify();
}
//线程1释放另一把锁
doSomething...
}
//线程1释放lockObj,此时线程0竞争到lockObj继续还行
}