简体   繁体   English

如何在Java中停止第3方方法?

[英]How to stop a 3rd party method, in java?

Let's say I have this code running in its own thread: 假设我在自己的线程中运行了以下代码:

SomeObject someObject = new SomeObject();
someObject.doLongTask();

That doLongTask() method can take a long time to finish. doLongTask()方法可能需要很长时间才能完成。 I also do not have the ability to modify its source. 我也没有能力修改其来源。 But I want to be able to terminate whatever it's doing, without killing the rest of my application. 但是我希望能够终止正在执行的任何操作,而又不会终止我的应用程序的其余部分。 How can I terminate that method while it's running? 如何在运行该方法时终止该方法?

First, I think you should read this article: Why is Thread.stop() Deprecated? 首先,我认为您应该阅读本文: 为什么不赞成使用Thread.stop()?

Because allowing threads to be killed at will by other threads can introduce many deadlock problems in multi-threaded code that are not easy to think about and mitigate ahead of time, the Java developers decided to not support this feature. 由于允许其他线程随意杀死线程会在多线程代码中引入很多死锁问题,这些问题很难事先考虑和缓解,因此Java开发人员决定不支持此功能。 However, there are ways you can get around this problem. 但是,有一些方法可以解决此问题。 Take a look at the code below, with the understanding that this may not actually be a full solution to your problem, depending on how doLongTask() is implemented: 请看下面的代码,了解这实际上可能不是您问题的完整解决方案,具体取决于doLongTask()的实现方式:

long timeout = ...//some number of milliseconds to wait
final SomeObject someObject = new SomeObject();
Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
        someObject.doLongTask();
    }
});
t.join(timeout);
if(t.isAlive()){
    t.interrupt();
    //handle failed task here;
}

This code assumes that SomeObject.doLongTask() is designed to look for thread interrupts periodically and terminate early if one is detected. 此代码假定SomeObject.doLongTask()设计为定期查找线程中断,并在检测到中断时提早终止。 Otherwise, t will continue to run doLongTask() until it completes. 否则, t将继续运行doLongTask()直至完成。 If doLongTask() isn't coded to handle thread interrupts and you don't have access to source code, you may be out of luck, short of running that long task in a separate process. 如果未将doLongTask()编码为处理线程中断,并且您无权访问源代码,则可能会遇到运气,因为无法在单独的进程中运行该长任务。

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

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