Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过创建线程池在运行JUnit测试脚本时在线程之间添加延迟_Java_Multithreading_Junit_Threadpool_Executorservice - Fatal编程技术网

Java 通过创建线程池在运行JUnit测试脚本时在线程之间添加延迟

Java 通过创建线程池在运行JUnit测试脚本时在线程之间添加延迟,java,multithreading,junit,threadpool,executorservice,Java,Multithreading,Junit,Threadpool,Executorservice,我正在尝试运行JUnit测试脚本,基本上所有测试脚本都是使用线程并行地与SeleniumWebDriver相关的,为此我使用ExecutorService创建了一个大小相同的线程池。下面是我创建线程池的代码 ExecutorService executor = Executors.newFixedThreadPool(4); for (int threadpoolCount = 0; threadpoolCount < classNames.size(); threadpoolCount+

我正在尝试运行JUnit测试脚本,基本上所有测试脚本都是使用线程并行地与SeleniumWebDriver相关的,为此我使用ExecutorService创建了一个大小相同的线程池。下面是我创建线程池的代码

ExecutorService executor = Executors.newFixedThreadPool(4);
for (int threadpoolCount = 0; threadpoolCount < classNames.size(); threadpoolCount++) {
        Runnable worker = new ProcessRunnable(classNames.get(threadpoolCount));
        executor.execute(worker);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }
}

我面临的问题是,尽管线程池在初始化时保持4个线程的大小,但它同时执行所有线程,这会在浏览器启动时产生一些同步问题。所以我的想法是在线程执行之间增加一些延迟


因为我正在线程池中创建一个新的可运行线程,所以我不确定如何在线程之间添加等待或延迟,我无法理解这个问题。请在这方面帮助我,非常感谢您的帮助。

如果您需要串行解决方案,如果您需要延迟,请使用Executors.newSingleThreadExecutor。否则,您可以按如下方式休眠线程:

Thread.sleep(1000L); //1 second (takes long, not int)
或者使用基于线程数递增的值

更好的解决方法是使用。您可以使用自定义静态或递增延迟提交它们。将核心大小设置为4,它的行为就像一个固定的线程池;从文件:

虽然此类继承自ThreadPoolExecutor,但 继承的优化方法对它没有用处。特别是因为 它使用corePoolSize线程和 无限队列,对maximumPoolSize的调整没有任何有用的效果。 此外,将corePoolSize设置为 零或使用allowCoreThreadTimeOut,因为这可能会离开池 没有线程来处理任务,一旦它们有资格运行


如果希望执行是同步的,为什么要使用线程?我正在尝试通过创建计数为4的线程池并行运行Junit测试脚本。我需要在每次启动之间添加几秒钟的延迟,以避免在启动浏览器时出现与浏览器相关的错误同步问题。如果我的想法错误,请纠正我,也可能请为我提供一个理想的解决方案来实现。
Thread.sleep(1000L); //1 second (takes long, not int)