直接调用wait()是调用哪个对象的wait().
JAVA API中 notify()方法的解释是 唤醒在此对象监视器上等待的单个线程。
如果当前没有等待的线程是不是这句代码相当于费的
wait()应该是对应线程的,它对释放对像的锁。这样其它线程就可以访问对像。
如果没有等待线程。那么调用notify()肯定什么都不做啊
千言万语顶不住一段代码:
package com.apkkids.thread;
class ThreadA extends Thread {
boolean flag = true;
public void threadExit() {
flag = false;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("ThreadA run " + i + " times");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ThreadA exit!");
synchronized (WaitNotifyTest.obj) {
WaitNotifyTest.obj.notify();
}
}
}
/**
* @author wxb
* Description:演示Java使用synchronized、wait和notify来实现线程的互相等待与通知
*
* 2015-6-27
* 下午9:07:35
*/
public class WaitNotifyTest {
public static Object obj = new Object();
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
threadA.start();
synchronized (WaitNotifyTest.obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Main Thread exit!");
}
}