我的程序有一个网站数组列表,我通过图像处理进行 I/O、从网站抓取数据并更新/插入数据库。现在速度很慢,因为所有 I/O 都已完成。我想通过允许我的程序使用线程运行来加快速度。列表中没有任何内容被删除,并且列表中的每个网站都是彼此独立的,因此对我来说,让实例同时循环列表以加快速度似乎是可以的。
假设我的列表有 10 个网站,现在当然它正在循环位置 0 到 9,直到我的程序完成对所有网站的处理。
假设我希望有 3 个线程同时循环访问这 10 个网站的列表,同时在各自单独的空间中执行所有 I/O 和数据库更新,但使用相同的列表。
website.get(0) // thread1
website.get(1) // thread2
website.get(2) // thread3
然后说,如果线程2到达循环末尾,它首先返回并在下一个位置工作
website.get(3) // thread2
然后thread3完成并获取下一个位置
website.get(4) // thread3
然后线程1最终完成并在下一个位置工作
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/