在 JAVA 中重复使用线程池
Repeatedly use a threadpool in JAVA
我正在调用 API 来获取 ID 列表。此列表包含大约 55.000 个 ID。然后我希望启动线程并根据 ID 获取有关其对象的信息并将其存储在数据库中。我已经设法使用线程完成此操作,但想知道如何使用线程池对其进行优化。
我想要创建 10 个线程,将它们添加到线程池中,等待它们完成,等待 10 秒(否则我将得到 429,请求太多),然后再启动 10 个线程直到全部完成.要做到这一点需要做什么?
此外,该列表的长度未知,因此最后一个池中可能不是 10 个项目,如果这有什么不同的话。
这就是我目前所做的工作。 (睡眠不是很有效,过了一会儿还是 429 发生了)
JSONObject IDs = getIDs();
for (int i = 0; i <= IDs.length(); i++) {
try {
int ID = IDs.getJSONArray("app").getInt("appid");
// get info on object and store it in database
Thread t = new Thread(new MyRunnable(ID));
t.start();
// sleep or 429, too many requests
Thread.sleep(1000);
} catch (JSONException | InterruptedException e) {
e.printStackTrace();
}
}
您可以使用 CyclicBarrier 来达到这个目的。
A synchronization aid that allows a set of threads to all wait for
each other to reach a common barrier point. CyclicBarriers are useful
in programs involving a fixed sized party of threads that must
occasionally wait for each other. The barrier is called cyclic because
it can be re-used after the waiting threads are released.
我正在调用 API 来获取 ID 列表。此列表包含大约 55.000 个 ID。然后我希望启动线程并根据 ID 获取有关其对象的信息并将其存储在数据库中。我已经设法使用线程完成此操作,但想知道如何使用线程池对其进行优化。
我想要创建 10 个线程,将它们添加到线程池中,等待它们完成,等待 10 秒(否则我将得到 429,请求太多),然后再启动 10 个线程直到全部完成.要做到这一点需要做什么?
此外,该列表的长度未知,因此最后一个池中可能不是 10 个项目,如果这有什么不同的话。
这就是我目前所做的工作。 (睡眠不是很有效,过了一会儿还是 429 发生了)
JSONObject IDs = getIDs();
for (int i = 0; i <= IDs.length(); i++) {
try {
int ID = IDs.getJSONArray("app").getInt("appid");
// get info on object and store it in database
Thread t = new Thread(new MyRunnable(ID));
t.start();
// sleep or 429, too many requests
Thread.sleep(1000);
} catch (JSONException | InterruptedException e) {
e.printStackTrace();
}
}
您可以使用 CyclicBarrier 来达到这个目的。
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.