java中的sleep和wait的区别

Python09

java中的sleep和wait的区别,第1张

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由线程自动唤醒,wait必须显示用代码唤醒。

sleep是Thread类的静态方法。sleep的作用是让线程休眠制定的时间,在时间到达时恢复,也就是说sleep将在接到时间到达事件事恢复线程执行,例如:

try{

System.out.println("I'm going to bed")

Thread.sleep(1000)

System.out.println("I wake up")

}

catch(IntrruptedException e) {

}

wait是Object的方法,也就是说可以对任意一个对象调用wait方法,调用wait方法将会将调用者的线程挂起,直到其他线程调用同一个对象的notify方法才会重新激活调用者,例如:

//Thread 1

try{

obj.wait()//suspend thread until obj.notify() is called

}

catch(InterrputedException e) {

}

sleep()方法是Thread类里面的,主要的意义就是让当前线程停止执行,让出cpu给其他的线程,但是不会释放对象锁资源以及监控的状态,当指定的时间到了之后又会自动恢复运行状态。

wait()方法是Object类里面的,主要的意义就是让线程放弃当前的对象的锁,进入等待此对象的等待锁定池,只有针对此对象调动notify方法后本线程才能够进入对象锁定池准备获取对象锁进入运行状态。