优化ThreadUtil.safeSleep,使用System.nanoTime()

This commit is contained in:
Looly 2024-03-26 18:13:46 +08:00
parent 8e26dd001b
commit 2f7938492e
3 changed files with 18 additions and 11 deletions

View File

@ -2,7 +2,7 @@
# 🚀Changelog # 🚀Changelog
------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------
# 5.8.27(2024-03-18) # 5.8.27(2024-03-26)
### 🐣新特性 ### 🐣新特性
* 【extra 】 FreemarkerEngine修改默认版本参数 * 【extra 】 FreemarkerEngine修改默认版本参数
@ -10,6 +10,7 @@
* 【core 】 HexUtil#format方法增加prefix参数issue#I93PU9@Gitee * 【core 】 HexUtil#format方法增加prefix参数issue#I93PU9@Gitee
* 【core 】 StrUtil.replace歧义修改为replaceByCodePointissue#I96LWH@Gitee * 【core 】 StrUtil.replace歧义修改为replaceByCodePointissue#I96LWH@Gitee
* 【core 】 FileUtil和PathUtil增加Resource重载issue#I97FJT@Gitee * 【core 】 FileUtil和PathUtil增加Resource重载issue#I97FJT@Gitee
* 【core 】 优化ThreadUtil.safeSleep使用System.nanoTime()issue#I9BMGK@Gitee
### 🐞Bug修复 ### 🐞Bug修复
* 【core 】 修复PathMover对目标已存在且只读文件报错错误问题issue#I95CLT@Gitee * 【core 】 修复PathMover对目标已存在且只读文件报错错误问题issue#I95CLT@Gitee

View File

@ -384,18 +384,14 @@ public class ThreadUtil {
public static boolean safeSleep(long millis) { public static boolean safeSleep(long millis) {
long done = 0; long done = 0;
long before; long before;
long spendTime; // done表示实际花费的时间确保实际花费时间大于应该sleep的时间
while (done >= 0 && done < millis) { while (done < millis) {
before = System.currentTimeMillis(); before = System.nanoTime();
if (false == sleep(millis - done)) { if (!sleep(millis - done)) {
return false; return false;
} }
spendTime = System.currentTimeMillis() - before; // done始终为正
if (spendTime <= 0) { done += (System.nanoTime() - before) / 1_000_000;
// Sleep花费时间为0或者负数说明系统时间被拨动
break;
}
done += spendTime;
} }
return true; return true;
} }

View File

@ -1,5 +1,6 @@
package cn.hutool.core.thread; package cn.hutool.core.thread;
import cn.hutool.core.util.RandomUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -11,4 +12,13 @@ public class ThreadUtilTest {
ThreadUtil.execute(() -> Assert.assertTrue(isValid)); ThreadUtil.execute(() -> Assert.assertTrue(isValid));
} }
@Test
public void safeSleepTest() {
final long sleepMillis = RandomUtil.randomLong(1, 1000);
// 随机sleep时长确保sleep时间足够
final long l = System.currentTimeMillis();
ThreadUtil.safeSleep(sleepMillis);
Assert.assertTrue(System.currentTimeMillis() - l >= sleepMillis);
}
} }