I am using a for
loop which run for 10 times and in each iteration driver move to different URL and loads a file which took 4 minutes to complete all 10 downloads. I was wondering if I could implement multi-threading in a for
loop so that it starts a different thread for each iteration to execute the download process.
我正在使用一个运行10次的for循环,并在每个迭代驱动程序中移动到不同的URL并加载一个文件,花了4分钟完成所有10次下载。我想知道我是否可以在for循环中实现多线程,以便它为每次迭代启动一个不同的线程来执行下载过程。
for(int i=1;i<=10;i++) {
WebDriver driver = new ChromeDriver(setChromePref(URL[i]));
obj_SjStrore = new SjStrore(driver);
driver.click.findelements(By.xpath("xpath string").click;
driver.close();
}
1 个解决方案
#1
0
Something like this should work.
这样的事情应该有效。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ParallelDownload implements Runnable {
private String url;
private String xpath;
public ParallelDownload(String url, String xpath) {
super();
this.url = url;
this.xpath = xpath;
}
@Override
public void run() {
WebDriver driver = new ChromeDriver();
driver.get(url);
driver.findElement(By.xpath(xpath)).click();
driver.close();
}
public static void main(String[] args) {
String url[] = new String[10];
String xpath[] = new String[10];
// create thread executor with pool of 10 threads
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
// Initialize a thread and execute
Runnable worker = new ParallelDownload(url[i], xpath[i]);
executor.execute(worker);
}
executor.shutdown();
// wait till all the threads stops executing
while (!executor.isTerminated()) {
}
}
}
#1
0
Something like this should work.
这样的事情应该有效。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ParallelDownload implements Runnable {
private String url;
private String xpath;
public ParallelDownload(String url, String xpath) {
super();
this.url = url;
this.xpath = xpath;
}
@Override
public void run() {
WebDriver driver = new ChromeDriver();
driver.get(url);
driver.findElement(By.xpath(xpath)).click();
driver.close();
}
public static void main(String[] args) {
String url[] = new String[10];
String xpath[] = new String[10];
// create thread executor with pool of 10 threads
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
// Initialize a thread and execute
Runnable worker = new ParallelDownload(url[i], xpath[i]);
executor.execute(worker);
}
executor.shutdown();
// wait till all the threads stops executing
while (!executor.isTerminated()) {
}
}
}