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

时间:2013-09-27 18:49:57

标签: java multithreading junit threadpool executorservice

我试图通过使用线程并行运行JUnit测试脚本(基本上所有测试脚本都与Selenium WebDriver相关),为此我使用 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()) {
    }

这是我的线程实现,它触发了Junit类

public class ProcessRunnable implements Runnable{
private String classNames;
public ProcessRunnable(String className) {
    this.classNames = className;
}

public void run() {
    try {
        Class testcase = Class.forName(classNames);
        JUnitCore.runClasses(testcase);

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

我面临的问题是虽然Threadpool维护了4个线程的初始化大小,它同时执行所有线程,这在浏览器启动时会产生一些同步问题。所以我的想法是在线程执行之间添加一些延迟。

由于我在线程池中创建了一个新的可运行线程,我不确定如何在线程之间添加等待或延迟,我无法解决这个问题。请帮助我,感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果您需要串行解决方案(如果需要延迟,可能需要),请使用Executors.newSingleThreadExecutor()。否则你可以sleep这样的线程:

Thread.sleep(1000L); //1 second (takes long, not int)

或使用根据您的threadcount增加的值。

更好的解决方案是使用ScheduledThreadPoolExecutor.schedule(Runnable)。您提交自定义(静态或增加)延迟。将核心大小设置为4,它将表现得像一个固定的线程池;来自doc:

  

虽然这个类继承自ThreadPoolExecutor,但有一些   继承的调优方法对它没用。特别是因为   它使用corePoolSize线程和一个固定大小的池   无界队列,对maximumPoolSize的调整没有任何有用的效果。   此外,将corePoolSize设置为几乎绝不是一个好主意   零或使用allowCoreThreadTimeOut,因为这可能会离开池   没有线程来处理任务,一旦他们有资格运行。