SystemClock.sleep()方法与Thread.sleep()方法的区别

最近在学习一个项目代码的过程中发现了许多延时的地方使用了sleep()方法,不禁感到奇怪,之前因为Thread.sleep()方法导致假死崩溃的情况让我吸取了教训,前辈是不会犯这种小错误的,心想难道SystemClock.sleep()有什么特殊之处?于是自己去翻看了下API。

sleep

added in   API level 1
void sleep (long ms)

Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedExceptioninterrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.

Parameters
ms long: to sleep before returning, in milliseconds of uptime.

谷歌文档对这个方法的说明是:在返回之前等待给定的毫秒数;和sleep(long)(这里指的是Thread.sleep()方法)类似,但是不抛出

InterruptedException;interrupt()事件被推迟到下一次中断操作。直到至少经过指定的毫秒数之后才会返回。


这里的关键点就是“不抛出InterruptedException”,也就是说不需要考虑在Thread.sleep()中出现的InterruptedException,而对InterruptedException的最常见的处理就是把它生吞掉——捕捉到然后并不做其他有效处理(可能会记录),这种做法埋下了一个巨坑——可能会导致中断的发生。而中断可能导致应用程序丧失及时取消活动或关闭的能力。这就意味着我们调用的方法是一个阻塞方法,需要花更大的代价来解决这个阻塞方法。所以SystemClock.sleep()方法的作用显而易见了,不考虑中断异常,可能发生的中断被推迟到下一次中断来临。


下面顺便也找出来了Thread.sleep()方法的说明,做下对比。

sleep

added in   API level 1
void sleep (long millis)

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.

Parameters
millis long: the length of time to sleep in milliseconds
Throws
IllegalArgumentException if the value of millis is negative
InterruptedException if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值