简体   繁体   English

Java:使用线程检查条件

[英]Java: Using a thread to check a condition

I have a problem I don't find how to solve. 我有一个我找不到解决方法的问题。 I have a main thread running two nested loops. 我有一个主线程运行两个嵌套循环。 The nested loop is executing business rules and checking a certain condition to know when it breaks. 嵌套循环正在执行业务规则,并检查特定条件以了解何时中断。

The problem here is this condition is time expensive and the goal of main program is to measure the time it takes, so checking this condition again and again introduces a skewness into the time measure. 这里的问题是这种情况是耗时的,并且主程序的目标是测量所花费的时间,因此一次又一次地检查这种情况会在时间测量中引入偏斜。

I think I could put the checker into an independent thread and when it is satisfied, notify to the main thread and get out from the nested loop. 我认为我可以将检查器放到一个独立的线程中,当它满足时,通知主线程并退出嵌套循环。 Is it possible? 可能吗?

Thanks 谢谢

Yes, it is possible and not that difficult. 是的,有可能,但没有那么困难。 All you have to do is to look into the future... (pun intended). 您要做的就是展望未来...(双关语)。 But seriously look into class Future . 但是,认真研究班级的未来 Read about it in the API (provided link) and may be search for usage examples, usually in conjunction with ExecutorService . 在API(提供的链接)中阅读有关它的信息,并且通常与ExecutorService结合使用,可以搜索使用示例。 This is exactly what you need. 这正是您所需要的。

Yes its possible. 是的,它有可能。 All you have to do is install third party plugin available for vs code or sublime whichever you prefer. 您所需要做的就是安装可用于vs代码或sublime的第三方插件。 You can check this on internet. 您可以在互联网上查看。 Then run your program this will show you exact time taken by your program. 然后运行您的程序,这将为您显示程序花费的确切时间。 For this testing purpose I suggest you run only one single thread you want to test. 为此,我建议您只运行一个要测试的单线程。

If you are doing this to measure the code performance/performance tuning go for JMH. 如果这样做是为了评估代码性能/性能调优,请使用JMH。
If you want to monitor you code block performance in runtime go for JFR or monitoring solution like Prometheus. 如果要监视运行时的代码块性能,请使用JFR或监视解决方案(例如Prometheus)。
If you have some use case which is dependent on duration of execution of this method then you can use CompletableFutures where main thread will start the code blocks it's dependent on and you can pass the callback which will be executed upon completion of all methods. 如果您有一些用例取决于此方法的执行时间,则可以使用CompletableFutures,在该方法中主线程将启动其依赖的代码块,并可以传递将在所有方法完成后执行的回调。

I don't think this is possible. 我认为这是不可能的。 You can control the thread-pool that executes your callback, but not the exact thread. 您可以控制执行回调的线程池,但不能控制确切的线程。 They do something like this in Android though: 他们在Android中做类似的事情:

Running code in main thread from another thread 从另一个线程在主线程中运行代码

On a side-note, the event loop in Javascript does what you want - takes the callbacks from the task queue, and pushes it to the main thread's call stack. 附带说明一下,Javascript中的事件循环可以完成您想要的工作-从任务队列中获取回调,并将其推入主线程的调用堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM