[英]How to join a schedule at fixed rate thread
If you have a an executor service which you submit via scheduleAtFixedRate such as this 如果您有执行服务,您可以通过scheduleAtFixedRate提交此类服务
public void methodName() {
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//do some operations
//getSomeResults()
}
}, x, y, TimeUnit.SECONDS);
}
Is it possible to join with another thread which is responsible for getSomeResults()? 是否可以与另一个负责getSomeResults()的线程一起加入? For example, I want the thread to wait for the getSomeResults() to finish before it continues - is this possible? 例如,我希望线程在继续继续之前等待getSomeResults()完成-这可能吗?
Thanks 谢谢
Yes, you want to submit a FutureTask
rather than a Runnable
. 是的,您要提交FutureTask
而不是Runnable
。 (A FutureTask
is a Runnable
, so you don't need to change anything else.) ( FutureTask
是Runnable
,因此您无需更改其他任何内容。)
If you create a FutureTask
then you can have another thread invoke its .get()
method, which will block until the task is complete, and it will return the result. 如果创建FutureTask
则可以让另一个线程调用其.get()
方法,该方法将阻塞直到任务完成为止,并且它将返回结果。
(The cleanest way will be to get rid of your getSomeResults()
method entirely, and just use the get()
method of FutureTask
; but there's nothing to stop you leaving your code more or less as it is, and just using get()
as a way of blocking, if you want to try that first to check it's all working.) (最干净的方法是完全摆脱getSomeResults()
方法,而仅使用FutureTask
的get()
方法;但是没有什么可以阻止您或多或少地保留代码,而只是使用get()
作为一种阻止方式,如果您想先尝试一下以检查其是否正常工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.