java的wait_wait()方法和notify()方法的使用

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()方法的基本使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值