gpt4 book ai didi

java - 对象的多线程数组列表

转载 作者:行者123 更新时间:2023-11-30 08:54:03 24 4
gpt4 key购买 nike

我的程序有一个网站数组列表,我通过图像处理进行 I/O,从网站抓取数据并更新/插入数据库。现在它很慢,因为所有的 I/O 都在完成。我想通过允许我的程序与线程一起运行来加快速度。列表中没有任何内容被删除,列表中的每个网站都是彼此分开的,所以对我来说,让实例同时循环遍历列表以加快速度似乎没问题。

假设我的列表是 10 个网站,现在它当然会从位置 0 到 9 循环,直到我的程序完成对所有网站的处理。

假设我想让 3 个线程同时循环遍历这个 10 个网站的列表,同时在它们自己的独立空间中执行所有 I/O 和数据库更新,但使用相同的列表。

website.get(0) // thread1
website.get(1) // thread2
website.get(2) // thread3

然后说如果 thread2 到达循环的末尾它首先返回并在下一个位置工作

website.get(3) // thread2

然后线程3完成并获得下一个位置

website.get(4) // thread3

然后 thread1 最终完成并处理下一个位置

website.get(5) // thread1

等等,直到完成。这容易设置吗?有什么地方可以找到一个很好的例子吗?我在网上查看过,试图找到其他地方谈论我的场景,但我没有找到。

最佳答案

在我的应用中,我像这样使用 ExecutorService,它运行良好:

主要代码:

ExecutorService pool = Executors.newFixedThreadPool(3); //number of concurrent threads

for (String name : website) { //Your ArrayList
pool.submit(new DownloadTask(name, toPath));
}

pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS); //Wait for all the threads to finish, adjust as needed.

您实际工作的类(class):

private static class DownloadTask implements Runnable {

private String name;
private final String toPath;

public DownloadTask(String name, String toPath) {
this.name = name;
this.toPath = toPath;
}

@Override
public void run() {
//Do your parsing / downloading / etc. here.

}
}

一些注意事项:

  • 如果您使用的是数据库,则必须确保不会有两个线程同时写入该数据库。

参见 here了解更多信息。

关于java - 对象的多线程数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29566121/

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