[英]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.