java中的wait和sleep_Java中的wait和sleep

sleep()和wait()

首先,Java中的多线程是一种抢占式的机制,而不是分时机制。抢占式的机制是有多个线程处于可运行状态,但是只有一个线程在运行。

这种机制决定了,对于同一对象的多线程访问,必须考虑同步的问题,synchronize的意义在这。

几个区别:

sleep是Thread类的方法,用于线程自身的控制;wait是Object类的方法,用于线程之间的控制,配套的方法是Object·的notify和notifyAll方法。

sleep与锁没有关系,如果在锁之中,不会释放锁。wait存在于锁之中,会释放当前的锁,等待被唤醒(notify)。

sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常 。但在 sleep的过程中过程中有可能被其他对象调用它的interrupt(),产生InterruptedException异常,如果你的程序不捕获这个异常,线程就会异常终止,进入TERMINATED状态,如果你的程序捕获了这个异常,那么程序就会继续执行catch语句块(可能还有finally语句块)以及以后的代码。注意sleep()方法是一个静态方法,也就是说他只对当前对象有效,不能通过t.sleep()让t对象进入sleep。

JDK8关于这两个的解释:

/**

* Causes the currently executing thread to sleep (temporarily cease

* execution) for the specified number of milliseconds, subject to

* the precision and accuracy of system timers and schedulers. The thread

* does not lose ownership of any monitors.

*/

public static native void sleep(long millis) throws InterruptedException;

sleep方法总结为:

使当前运行的线程休眠,该线程不会丢失对任何监视器的所有权。

/**

* Causes the current thread to wait until another thread invokes the

* {@link java.lang.Object#notify()} method or the

* {@link java.lang.Object#notifyAll()} method for this object.

* In other words, this method behaves exactly as if it simply

* performs the call {@code wait(0)}.

*

* The current thread must own this object's monitor. The thread

* releases ownership of this monitor and waits until another thread

* notifies threads waiting on this object's monitor to wake up

* either through a call to the {@code notify} method or the

* {@code notifyAll} method. The thread then waits until it can

* re-obtain ownership of the monitor and resumes execution.

*

* As in the one argument version, interrupts and spurious wakeups are

* possible, and this method should always be used in a loop:

*

 
 

* synchronized (obj) {

* while (<condition does not hold>)

* obj.wait();

* ... // Perform action appropriate to condition

* }

*

public final void wait() throws InterruptedException {

wait(0);

}

wait方法总结为:

使当前线程等待,直到另外线程唤醒被锁对象的notify或notifyAll方法。当前线程,必须拥有当前对象的监视器,当wait时,释放这种拥有关系,直到其他线程唤醒此对象的notify或notifyAll方法,此时线程重新获得这种拥有关系,并继续执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值