java中的sleep和wait的区别
sleep和wait的区别:
1、sleep的意思是:睡,睡觉,睡眠。
2、wait的意思是:等候,推迟,延缓等待,耽搁,伺候用餐。
sleep的用法
1、They were exhausted from lack of sleep?
由于缺乏睡眠,他们非常疲惫。
2、During the car journey, the baby slept?
坐车来的路上,宝宝睡着了。
3、I think he may be ready for a sleep soon.?
我想他也许很快就要睡一觉了。
4、I can't get to sleep with all that singing.?
那些歌声搅得我无法入睡。
5、I didn't lose too much sleep over that investigation.?
我并不太担心那个调查。
wait
1、I walk to a street corner and wait for the school bus?
我走到街角等校车。
2、There'll be a car waiting for you?
会有辆汽车等你。
3、I want to talk to you, but it can wait?
我想和你谈谈,但可以晚点再说。
4、If you think this all sounds very exciting, just wait until you read the book?
如果你觉得所有这些听起来令人兴奋,那就等着去读这本书吧。
5、'Wait a minute!' he broke in. 'This is not giving her a fair hearing!'?
“等一下,”他插嘴说,“这没有给她一个公平的解释机会!”
首先,sleep()是Thread类中的方法,而wait()则是Object类中的方法。
sleep()方法导致了程序暂停,但是他的监控状态依然保持着,当指定的时间到了又会自动恢复运行状态。在调用sleep()方法的过程中,线程不会释放对象锁。
wait()方法会导致线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
以下以代码为例讲解:
package test;
public class WaitAndSleep {
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable {
@Override
public void run() {
synchronized (WaitAndSleep.class) {
System.out.println("thread1 is waiting...");
try {
// 调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池
WaitAndSleep.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is going on ....");
System.out.println("thread1 is over!!!");
}
}
}
private static class Thread2 implements Runnable {
@Override
public void run() {
synchronized (WaitAndSleep.class) {
System.out.println("enter thread2....");
System.out.println("thread2 is sleep....");
// 只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
WaitAndSleep.class.notify();
// ==================
// 区别
// 如果我们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,但是没有调用notify()
// 方法,则线程永远处于挂起状态。
try {
// sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,
// 但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
// 在调用sleep()方法的过程中,线程不会释放对象锁。
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going on....");
System.out.println("thread2 is over!!!");
}
}
}
}
运行结果:
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!
如果我们把代码:WaitAndSleep.class.notify();给注释掉
运行结果:
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
程序一直处于挂起状态,无法结束
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!