简体   繁体   English

是否可以在Java中的指定时间内停止函数的执行?

[英]Is it possible to stop a function's execution within a specified time in Java?

I want to know how to stop a specified function's execution within a specified time in java. 我想知道如何在java中的指定时间内停止指定函数的执行。

For example: I may call a function called print_data(). 例如:我可以调用一个名为print_data()的函数。 If it takes more time to execute, I will have to stop that function's execution. 如果执行需要更多时间,我将不得不停止该函数的执行。

Is it possible to stop the execution like this? 可以像这样停止执行吗?

Thanks in advance 提前致谢

You could add some checks to your function: save the timestamp when function started working and then periodically checking that inside the function, throwing an exception if function takes too long. 您可以为函数添加一些检查:保存函数开始工作时的时间戳,然后定期检查函数内部,如果函数需要太长时间则抛出异常。

This is the cleanest way to accomplish such task in Java. 这是在Java中完成此类任务的最简洁方法。

There is no safe way to stop a thread executing, unless it is being cooperative; 没有安全的方法来阻止线程执行,除非它是合作的; eg it regularly checks the 'interrupted' flag. 例如,它会定期检查“中断”标志。

@BobbyShaftoe suggests this in a comment: @BobbyShaftoe在评论中暗示:

You could execute this function in a separate thread and then abort the thread after some period of time. 您可以在单独的线程中执行此函数,然后在一段时间后中止该线程。

This is misleading and dangerous advice. 这是误导性和危险的建议。 The only way to "abort" a thread is to use the deprecated Thread.stop() method. “中止”线程的唯一方法是使用不推荐使用的Thread.stop()方法。 If you look at the javadoc for that method you will see that it is a fundamentally dangerous method that is liable to have undesirable and unpredictable side-effects. 如果你看一下该方法的javadoc ,你会发现它是一种根本危险的方法,容易产生不良和不可预测的副作用。

It should also be noted that @tonio's solution doesn't stop the function's execution. 还应该注意,@ tonio的解决方案不会停止函数的执行。 It simply stops waiting for the function's execution to finish. 它只是停止等待函数的执行完成。 The function could continue executing indefinitely, chewing up resources to no good effect. 该功能可以无限期地继续执行,将资源扼杀到没有好的效果。

You can use the TimeUnit enum from java.util.concurrent , in particular the timedJoin method. 您可以使用java.util.concurrentTimeUnit枚举 ,特别是timedJoin方法。

You specify a time to wait, and a thread. 您指定等待的时间和线程。 timedJoin will let your thread execute until termination, or stop if the processing takes more time than the timeout allowed. timedJoin将让你的线程执行直到终止,或者如果处理花费的时间超过允许的超时时停止。 You can use an anonymous class to wrap your method in a Thread object easily. 您可以使用匿名类轻松地将方法包装在Thread对象中。

This can be as easy as: 这可以很简单:

SECONDS.timedJoin(
    new Thread() {
      public void run() {
        print_data();
      }
    },
    10);    

for a 10 seconds timeout. 10秒超时

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

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