[英]How to limit the execution time of a third-party Java method
In a Java program I need to execute a method of a third-paryt java class. 在Java程序中,我需要执行第三个paryt java类的方法。 I use Class.forName
to get a class and newInstance()
to get an object of this class: 我使用Class.forName
获取类和newInstance()
来获取此类的对象:
Class class = Class.forName(className);
AClass object = (AClass) class.newInstance();
Then I execute and get a result of the desired method with 然后我执行并获得所需方法的结果
ResultObject result = object.method();
So far, so good. 到现在为止还挺好。 But the problem appears if I want to limit the execution time of the method (ie, if the method doesn't stop after a given number of seconds, I would like to kill this execution and ignore the result). 但是如果我想限制方法的执行时间(例如,如果方法在给定的秒数后没有停止,我想要终止此执行并忽略结果),则会出现问题。
An ideal solution would be to run the method in a separate thread and to stop&destroy this thread if the method doesn't finish in time. 理想的解决方案是在单独的线程中运行该方法,并在方法未及时完成时停止并销毁此线程。 But unfortunately a thread CAN NOT BE STOPED (it's stop()
method is deprecated) and I can not rely on correct interrupt-behaviour of the third-party method. 但不幸的是,一个线程无法stop()
(它的stop()
方法已被弃用)并且我不能依赖第三方方法的正确中断行为。
Is there any other way to execute a method and to have a full control over its execution (ie to be able to kill it any time)? 有没有其他方法来执行一个方法并完全控制它的执行(即能够随时杀死它)? I am sure that this is possible - Netbeans, for example, can execute my class (when I run my application) and it can kill it if I press stop button. 我确信这是可能的 - 例如,Netbeans可以执行我的类(当我运行我的应用程序时)并且如果我按下停止按钮它可以杀死它。 But how does Netbeans (or Eclipse or any othe IDE) manage to do this? 但Netbeans(或Eclipse或任何其他IDE)如何设法做到这一点?
Any idea? 任何的想法? Thanks! 谢谢!
One option would be to run the 3rd party code not just in a seperate thread, but in a seperate process. 一种选择是不仅在单独的线程中运行第三方代码,而且在单独的进程中运行。 It's a hassle, but you can kill the process whenever you want to and it's guaranteed to work. 这是一个麻烦,但你可以随时杀死这个过程,并保证工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.