【发布时间】:2019-06-27 06:48:15
【问题描述】:
我试图让 selenium webdriver 的 5 个线程在给定时间运行,等待这些线程完成,然后再打开 5 个,重复直到运行约 200 个线程。我的代码可以打开 5 个线程并等待它们完成,然后再继续,但是当我尝试将其放入循环并将目标设置为 10 个线程时(应该是 5 个运行并完成的线程,然后是 5 个运行并完成的线程之后),它同时打开所有 10 个线程。我担心如果我将目标提高到 200 个线程,它会使计算机过载。
根据对此处提出的另一个问题的回答(终生无法找到),我从使用 Thread 切换到 ExecutorService,后者用于知道 5 个线程何时完成。我不是很有经验,所以除了 for/do-while/while 循环(我都尝试过)我不知道我可以尝试什么其他循环。
LISTSPERSESSION = 10;
ExecutorService es = Executors.newCachedThreadPool();
int listIndex = 0;
do {
boolean finished = false;
//Goes until 5 lists are searched OR the number of lists per session is hit
for(int i=0; i < 5 || listIndex < LISTSPERSESSION; i++) {
listIndex++;
int index = i;
es.execute(() -> v.searchDatabase(index));
}
es.shutdown();
try {
finished = es.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(finished == true) {
if(listIndex == LISTSPERSESSION) {
break;
} else {
continue;
}
}
} while(false);
它一次打开所有 10 个线程,而不是一次打开 5 个。
【问题讨论】:
标签: java multithreading selenium-webdriver executorservice