wait()方法的作用是让当前线程进行等待也就是让线程停止执行,并且wait()方法方是Object里的方法所有的对象默认都有此方法。
notify()方法的作用是让已经被wait()方法停止的线程继续执行,notify()方法和wait()方法一样也是Object里的方法。
下面我们简单演示它们之间的使用。
/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin extends Thread {
private Object lock;
public RequestAdmin(Object lock) {
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
System.out.println(String.format("start wait time: %s", System.currentTimeMillis()));
lock.wait();
System.out.println(String.format("end wait: %s", System.currentTimeMillis()));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestUser extends Thread {
private Object lock;
public RequestUser(Object lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
System.out.println(String.format("start notify time: %s", System.currentTimeMillis()));
lock.notify();
System.out.println(String.format("end notify: %s", System.currentTimeMillis()));
}
}
}
/**
* 测试类
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:49
* @since 1.0.0
*/
public class RequestRun {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
RequestAdmin requestAdmin = new RequestAdmin(lock);
RequestUser requestUser = new RequestUser(lock);
requestAdmin.start();
Thread.sleep(1000);
for (int i = 3; i > 0; i--) {
System.out.println(String.format("倒计时:%s", i));
Thread.sleep(1000);
}
requestUser.start();
}
}
start wait time: 1489722146812
倒计时:3
倒计时:2
倒计时:1
start notify time: 1489722150842
end notify: 1489722150842
end wait: 1489722150842
我们看到线程执行完start后线程停止了,只有另一个线程执行notify()方法时,中止的线程才恢复运行。这就是wait()方法和notify()方法的基本使用。