Java通过调用main创建线程

发布于 2024-09-19 08:03:30 字数 178 浏览 4 评论 0原文

我有一个客户端服务器应用程序,出于测试目的,我需要通过调用

Client.main();

创建一些新线程来在测试方法中启动客户端。现在我需要等到该线程完成后再在测试中执行断言。我怎么知道什么时候会发生这种情况?或者,我如何知道调用启动了哪个线程(客户端也可以创建其他线程)。

I have a client server application and for testing purposes I need to start the client in a test method by calling

Client.main();

That creates some new thread. Now I need to wait until that thread is completed before performing assertions in my test. How do I know when this happens? Alternatively, how do I know, which thread was started by the call (the client can create other threads too).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

国粹 2024-09-26 08:03:30

以编程方式调用 main 不会自行启动新线程。仅当 main 方法具有显式启动新线程的代码时才会发生这种情况。如果是这种情况,您应该更改 Client 以某种形式提供对此线程的访问,以便您可以对其调用 join()。 (调用 Thread.join() 是等待线程完成的标准方法。)

Client.main() 是否执行任何任务其他 比开始一个新线程?如果没有,您的测试可能会更简单,只需调用新线程最终运行的任何 run() 方法,并尽可能使测试成为单线程。

Calling main programmatically won't start a new thread on its own. That would only happen if the main method has code to explicitly start a new thread. If that's the case, you should change Client to provide access to this thread in some form, so you can call join() on it. (Calling Thread.join() is the standard way of waiting for a thread to finish.)

Does Client.main() perform any tasks other than starting a new thread? If not, it would probably be simpler for your tests to just call whatever run() method the new thread will end up running, and making the test single-threaded as far as possible.

吃不饱 2024-09-26 08:03:30

您可以使用join()来等待其他线程完成执行。

You can use join() for waiting for other thread to finish execution.

勿挽旧人 2024-09-26 08:03:30

从未尝试过,但它可以适用于您的特殊情况。 Thread 有一个静态方法来获取所有活动线程的堆栈跟踪,使用此方法您可以获得一组线程对象。在调用 main 之前和之后调用它应该允许您获取对执行 main 方法时已创建/启动的所有线程的引用:

 Set<Thread> before = Thread.getAllStackTraces().keySet();
 Client.main();
 Set<Thread> after = Thread.getAllStackTraces().keySet();

当然,识别您的线程甚至更容易(并且更可靠),如果您的线程是使用唯一的 ID/名称创建的。现在您可以计算差异并在所有这些线程上调用 join。它可能有很多副作用,但是,如上所述,可能对您的特定测试用例有所帮助。

Never tried it but it could work in your special case. Thread has a static metod to get stacktraces for all live threads and with this method you get a Set of thread objects. Calling it before and after calling main should allow you to get references to all threads that have been created/started while the main method executed:

 Set<Thread> before = Thread.getAllStackTraces().keySet();
 Client.main();
 Set<Thread> after = Thread.getAllStackTraces().keySet();

Of course, identifying your threads is even easier (and more reliable) if your threads are created with unique IDs/names. Now you can calculate the difference and call join on all those threads. It may have a hell of sideeffects but, as mentioned above, may help in your specific test case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文