gpt4 book ai didi

android - Kotlin/anko 多个异步任务

转载 作者:搜寻专家 更新时间:2023-11-01 08:34:54 24 4
gpt4 key购买 nike

我正在寻找一种简单的方法来并行启动多个任务并等待所有任务完成。

考虑这个 C# 示例:

private static void Main(string[] args)
{
var urlList = new[] {"http://www.microsoft.com/", "http://www.google.com/", "http://www.apple.com/" };
var result = GetHtml(urlList);
}

private static List<string> GetHtml(string[] urlList)
{
var tasks = new List<Task>();
var output = new List<string>();

foreach (var url in urlList)
{
var task = new Task(() =>
{
var html = new WebClient().DownloadString(url);
output.Add(html);
});

tasks.Add(task);

//starts task in a separate thread (doesn't block anything)
task.Start();
}

//waits for all tasks (running in parallel) to complete before exiting method
Task.WaitAll(tasks.ToArray());

return output;
}

GetHtml 方法并行下载多个网页并返回 html 字符串列表。

我如何使用 kotlin/anko 实现这一点?

private fun GetHtml(urlList: Array<String>): ArrayList<String> {

val tasks = ArrayList<Future<Unit>>()
val output = ArrayList<String>()

for (url in urlList) {
val task = async() {
//some java-code that downloads html from <url>, doesn't matter for now
output.add("html for $url")
}
tasks.add(task)
}

//this is NOT parallel execution
for (task in tasks) {
task.get()
}

//tasks.getall() ??

return output
}

最佳答案

基于来自 Michael 的输入和 pdegand59 ,这是一个可行的解决方案:

private fun GetHtml(urlList: Array<String>): ArrayList<String> {

val pool = Executors.newFixedThreadPool(urlList.count())
val countDownLatch = CountDownLatch(urlList.count())

val output = ArrayList<String>()

for (url in urlList) {

async(pool, {
//some java-code that downloads html for <url>
output.add("html for $url")
countDownLatch.countDown()
})
}

countDownLatch.await()

return output
}

关于android - Kotlin/anko 多个异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com