我正在使用 withContext 将函数转换为不会阻塞调用线程的挂起函数。为此,我使用https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761作为参考。
现在我想调用这个函数并设置超时。为此,我使用 withTimeout 来调用该函数,如下所示:
@Test
internal fun timeout() {
runBlocking {
logger.info("launching")
try {
withTimeout(1000) {
execute()
}
} catch (e: TimeoutCancellationException) {
logger.info("timed out", e)
}
}
}
private suspend fun execute() {
withContext(Dispatchers.IO) {
logger.info("sleeping")
Thread.sleep(2000)
}
}
Run Code Online (Sandbox Code Playgroud)
所以我期望的是,在 1000 毫秒后,异步启动的协程将被取消,并引发 TimeoutCancellationException。
但发生的情况是,完整的 2000 毫秒经过,当协程完成时,抛出异常:
14:46:29.231 [main @coroutine#1] INFO btccCoroutineControllerTest - 启动
14:46:29.250 [DefaultDispatcher-worker-1 @coroutine#1] INFO btccCoroutineControllerTest - 睡眠
14:46:31.261 [main@coroutine#1] INFO btccCoroutineControllerTest - kotlinx.coroutines.TimeoutCancellationException 超时:在 kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:128) 在 kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:94) 在 kotlinx.coroutines 等待 1000 毫秒超时。 …
假设有一大堆范围.例如,大小为5000的集合:
[100,200],[1,59],[3,5],[70,70]...
Run Code Online (Sandbox Code Playgroud)
如何在Java中检查整数n是否有效地落入这些范围中的至少一个?