【问题标题】:How to start a thread for an operation at each iteration of for loop?如何在 for 循环的每次迭代中为操作启动一个线程?
【发布时间】:2017-09-26 12:07:58
【问题描述】:

我正在使用一个运行 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();
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读网站规则,以及:HOw to ask。你不会在这里得到问题的直接答案;编写代码,如果您遇到问题,我们会为您解决。
  • 是的,你可以。您在每次迭代中创建一个新的Thread,为每个人提供一个Runnable 来完成某项工作,启动线程,将所有线程对象存储在某个集合中,然后在循环之后等待所有存储的线程完成.
  • 或者,使用ExecutorService 或类似的东西。

标签: java multithreading loops selenium for-loop


【解决方案1】:

这样的事情应该可以工作。

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()) {
        }

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 2021-10-29
    • 2015-05-09
    • 2018-02-13
    • 2013-10-27
    • 2010-12-28
    • 2021-06-30
    • 2021-04-13
    相关资源
    最近更新 更多