gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:46:50 26 4
gpt4 key购买 nike

我在项目中导入了第三方库,现在我们将其发布到Websphere上(我使用ServletContextListener来清理应用程序中的所有步骤,使用Thread.stop( ) 方法),但是每次我们重新部署这个应用程序时,我发现旧线程仍然存在,我在互联网上搜索,并且知道它应该使用 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()可以停止线程,并且使用本地jetty,我可以重现问题,谁能解释一下?


我本地的测试代码:

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 教程 - Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

引用段落:

What should I use instead of Thread.stop? For example, suppose your applet contains the following start, stop and run methods:

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();
}
}

You can avoid the use of Thread.stop by replacing the applet's stop and run methods with: private volatile Thread blinker;

public void stop() {
blinker = null;
}

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

为什么不扩展第三方类,重写线程方法呢?

关于java - 如何杀死从第三方库导入的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com