2016-11-09 66 views
2

我想在我的Cucumber-JVM程序中创建一个新线程,当我达到某个BDD步骤时,创建一个新线程Java程序在线程完成之前退出。我如何让Cucumber-JVM等待线程退出?

然后,一个线程应该做一些事情,而最初的主线程继续贯穿黄瓜步骤。

程序不应该退出,直到所有线程都完成。

我遇到的问题是主程序在线程完成之前退出。

这里发生的事情:


输出/问题

  • 主程序RunApiTest
  • 线程类ThreadedSteps

这是当我运行该程序会发生什么:

  1. RunApiTest开始通过所有准备步骤
  2. RunApiTest到达
  3. RunApiTest现在创建“我应该会在5分钟之内收到一封电子邮件”一个线程ThreadedSteps,应该睡5分钟。
  4. ThreadedSteps开始睡5分钟
  5. 虽然ThreadedSteps正在睡觉,RunApiTest继续运行黄瓜BDD的其余步骤
  6. RunApiTest完成并退出,无需等待ThreadedSteps完成

如何让我的程序等待,直到我的线程完成?


这里是我的代码

主要黄瓜类RunApiTest

@RunWith(Cucumber.class) 
@CucumberOptions(plugin={"pretty"}, glue={"mycompany"}, features={"features/"}) 
public class RunApiTest { 
} 

黄瓜步骤来触发线程email_bdd

@Then("^I should receive an email within (\\d+) minutes$") 
public void email_bdd(int arg1) throws Throwable { 
    Thread thread = new Thread(new ThreadedSteps(arg1)); 
    thread.start(); 
} 

Thread类ThreadedSteps

public class ThreadedSteps implements Runnable { 

    private int seconds_g; 

    public ThreadedSteps(Integer seconds) { 
     this.seconds_g = seconds; 
    } 

    @Override 
    public void run() { 
     Boolean result = waitForSecsUntilGmail(this.seconds_g); 
    } 

    public void pauseOneMin() 
    { 
     Thread.sleep(60000); 
    } 

    public Boolean waitForSecsUntilGmail(Integer seconds) 
    { 
     long milliseconds = seconds*1000; 
     long now = Instant.now().toEpochMilli(); 
     long end = now+milliseconds; 

     while(now<end) 
     { 
      //do other stuff, too 
      pauseOneMin(); 
     } 
     return true; 
    } 
} 

尝试#1

我尝试添加join()到我的线程,但停止我的主要程序的执行,直到线程已完成,然后继续执行程序的其余部分。这不是我想要的,我希望线程在主程序继续执行时进入睡眠状态。

@Then("^I should receive an email within (\\d+) minutes$") 
public void email_bdd(int arg1) throws Throwable { 
    Thread thread = new Thread(new ThreadedSteps(arg1)); 
    thread.start(); 
    thread.join(); 
} 

回答

2

thread.join()的确如此 - 它需要程序停止执行,直到该线程终止。如果你想让你的主线程继续工作,你需要把你的join()放在代码的底部。这样,主线程可以完成它的所有任务,然后然后等待你的线程。

+0

是的,我给'RunApiTest'添加了一个'@ AfterClass'并添加了'join()',并且它最后运行了,但是这个步骤的结果保存错了......我想我只是要去改为使用maven parellel插件。 https://github.com/temyers/cucumber-jvm-parallel-plugin – Kayvar

相关问题