Java通过调用main创建线程
我有一个客户端服务器应用程序,出于测试目的,我需要通过调用
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以编程方式调用
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 themain
method has code to explicitly start a new thread. If that's the case, you should changeClient
to provide access to this thread in some form, so you can calljoin()
on it. (CallingThread.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 whateverrun()
method the new thread will end up running, and making the test single-threaded as far as possible.您可以使用
join()
来等待其他线程完成执行。You can use
join()
for waiting for other thread to finish execution.从未尝试过,但它可以适用于您的特殊情况。
Thread
有一个静态方法来获取所有活动线程的堆栈跟踪,使用此方法您可以获得一组线程对象。在调用 main 之前和之后调用它应该允许您获取对执行 main 方法时已创建/启动的所有线程的引用:当然,识别您的线程甚至更容易(并且更可靠),如果您的线程是使用唯一的 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: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.