繁体   English   中英

如何杀死从第三方库导入的线程?

[英]How to kill a thread imported from third-party lib?

我在项目中导入了第三方库,现在我们将其发布在Websphere上(我使用ServletContextListener清理应用程序中的所有踩踏,使用Thread.stop()方法),但是每次我们重新部署此应用程序时,我都发现旧线程仍然存在,我在Internet上搜索了一下,知道它应该使用voilate成员或与interrupt()一起使用 ,但是我不想破解第三方lib,所以谁能给我提示?
谢谢:)
第三方库代码如下:

public void run() {
      while (true) {
            try {
                for (DefaultFuture future : FUTURES.values()) {
                    if (future == null || future.isDone()) {
                        continue;
                    }
                    if (System.currentTimeMillis() - future.getStartTimestamp() > future.getTimeout()) {
                        // create exception response.
                        Response timeoutResponse = new Response(future.getId());
                        // set timeout status.
                        timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT);
                        timeoutResponse.setErrorMessage(future.getTimeoutMessage(true));
                        // handle response.
                        DefaultFuture.received(future.getChannel(), timeoutResponse);
                    }
                }
                Thread.sleep(30);
            } catch (Throwable e) {
                logger.error("Exception when scan the timeout invocation of remoting.", e);
            }
        }
    }

我做了一个简单的本地测试,发现thread.stop()可以停止线程,并使用本地码头,我可以重现该问题,谁能解释呢?


我的本地测试代码:

public class Test {
public static void main(String[] args) throws InterruptedException, IOException {
    myThread t1 = new myThread();
    t1.start();
    Thread.sleep(4000);
    t1.stop();
    System.in.read();
}

}

class myThread extends Thread{
@Override
public void run() {
    int i=0;
    while(true){
        try {
            System.out.println(i++);
            Thread.sleep(30);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

}

不建议使用stop方法。 这是不安全的。 您应该阅读Oracle教程- 为什么不赞成使用Thread.stop,Thread.suspend和Thread.resume?

请参阅以下段落:

我应该用什么代替Thread.stop? 例如,假设您的小程序包含以下start,stop和run方法:

 private Thread blinker; public void start() { blinker = new Thread(this); blinker.start(); } public void stop() { blinker.stop(); // UNSAFE! } public void run() { while (true) { try { Thread.sleep(interval); } catch (InterruptedException e){ } repaint(); } } 

您可以通过将applet的stop和run方法替换为以下方法来避免使用Thread.stop:

 public void stop() { blinker = null; } public void run() { Thread thisThread = Thread.currentThread(); while (blinker == thisThread) { try { Thread.sleep(interval); } catch (InterruptedException e){ } repaint(); } } 

为什么不扩展第三方Class,然后重新编写thread方法?

暂无
暂无

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

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