【发布时间】:2020-10-26 16:20:44
【问题描述】:
我在 Kotlin 中有简单的代码,它使用 okhttp lib 列出了请求 (150),并且我使用 JSOUp 解析了每个 html 结果。
我用的是协程但是不懂,有没有协程的时间都是一样的(23秒)
也许我做了坏事?还是http请求受限?
我的代码:
fun parse(list: ArrayList<ChampionBean>) {
runBlocking {
list.forEach {
launch {
val response = requestWithOkhttp(it.url)
val doc = Jsoup.parse(response.body?.string())
response.close()
parsedocwithJsoup(doc, it)
}
}
}
}
【问题讨论】:
-
几件事。您在那里的协程将继承上下文,因此您可能有一个只有 1 个线程的上下文。您可以打印
println("I'm working in thread ${Thread.currentThread().name}")来查找线程名称。另外 okhttpclient 是如何配置的?因为它可以配置为只使用一个 http 连接。 -
感谢您的回答@Augusto,我所有的发布都在同一个线程上。我用启动解决了我的问题(Dispatchers.Default)
-
@Tenfour04 这是一个脚本,目的是等待所有请求完成。 runblocking 的主要作用是等待内部的所有启动/异步
标签: kotlin kotlin-coroutines coroutine