Java程序在线程完成之前退出.我如何使Cucumber-JVM等待线程退出?



我正在尝试在我的黄瓜jvm程序中创建一个新线程,当我达到某个BDD步骤时

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

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

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

是这样的:


输出/问题

  • 主程序RunApiTest
  • 线程类ThreadedSteps

下面是我运行程序时的结果:

  1. RunApiTest开始通过所有步骤
  2. RunApiTest到达"我应该在5分钟内收到一封电子邮件"
  3. RunApiTest现在创建一个线程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();
}

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

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

最新更新