Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
限速失败问题
背景
下载时发现调用限速接口时,限速不准确,接口无法调用。
在设置限速之后还会出现下载速度总是处于100Kb以下的情况。
https://github.com/AriaLyy/Aria/issues/884
问题复现
通过打log定位问题,最终发现是线程睡眠时间不准确导致的。
指定的睡眠时间是0.973489ms,但是实际上睡了41.95401ms。
限速就是通过控制线程睡眠时间来达到控制接收传输字节流速度的,如果sleep睡眠时间与指定的不一致就会出现限速不准确,会有10~40ms的差异。
同时,一旦进行了限速就会一直触发这个问题,所以才会有背景中提到的,一旦设置限速之后网速一直小于100Kb/s。
问题分析
Android系统中,后台线程调用sleep之后由于优先级较低,不能及时抢占cpu资源,所以会导致睡眠时间与指定的时间不符。
进一步验证:
编写demo验证
当应用处于前台时:睡眠时间基本准确。
当应用退到后台,也会出现睡眠时间不准确的现象。
问题解决
线程的优先级受到应用生命周期的影响,当应用退到后台对应的线程游戏级会降低。
同时,还可以显式设置线程的优先级来保证功能的正常。
下载的优先级从后台调整为默认之后,限速功能正常。