【问题标题】:Java program exits before thread has finished. How do I make Cucumber-JVM wait for the thread to exit?Java 程序在线程完成之前退出。如何让 Cucumber-JVM 等待线程退出?
【发布时间】:2016-11-09 23:06:02
【问题描述】:

我正在尝试在我的 Cucumber-JVM 程序中创建一个新线程当我达到某个 BDD 步骤时

然后,一个线程应该做某事,而原来的主线程继续运行黄瓜步骤。

在所有线程完成之前,程序不应退出。

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

这是发生了什么:


输出/问题

  • 主程序RunApiTest
  • 线程类ThreadedSteps

这是我运行程序时发生的情况:

  1. RunApiTest 开始执行所有步骤
  2. RunApiTest 得到“我应该在 5 分钟内收到一封电子邮件”
  3. RunApiTest 现在创建一个线程 ThreadedSteps,它应该休眠 5 分钟。
  4. ThreadedSteps 开始睡眠 5 分钟
  5. ThreadedSteps 处于睡眠状态时,RunApiTest 继续运行其余的 Cucumber 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();
}

线程类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();
}

【问题讨论】:

    标签: java multithreading cucumber cucumber-jvm cucumber-java


    【解决方案1】:

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

    【讨论】:

    • 是的,我在RunApiTest 中添加了@AfterClass 并在其中添加了join(),它最后运行,但步骤的结果保存错误...我想我是只是要使用 maven parellel 插件代替。 github.com/temyers/cucumber-jvm-parallel-plugin
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多