java运行多线程并在异常时停止线程
我有一个来自许多分支官员的线程(实现Runnable),用分支代码调用该线程。我用分支代码设置了他们线程的名称。 问题是
- 当运行线程时发生异常-我无法停止。当尝试创建另一个名为“ExceptionInInitializeError”或“OutOfMemoryError:Java堆空间”的线程时
- “OutOfMemoryError:Java堆空间”异常在一次运行两个或多个线程时出现李>
public MyRunnerClass {
//This method called from many branch with their branch Code
public void executeBranchProcess(String branchCode){
Thread t = new Thread(new Exporter(branchCode);
t.setName(branchCode);
t.start();
}
}
线程类在这里
public class Exporter implements Runnable{
private String branchCode;
public Exporter(String branchCode){
this.branchCode = branchCode;
}
@Override
public void run() {
try {
exportCorner();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void exportCorner() throws InterruptedException{
try{
//Some Process
}catch(Exception e){
// I want to close running thread here
// I am using closeThread(this.branchCode), but not working
}
}
static void closeThread(String branchCode) throws InterruptedException {
Thread thread = null;
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(branchCode))
thread = t;
}
if (thread != null) {
thread.interrupt();
thread.join();
}
}
}
# 1 楼答案
你在这里面临多个问题:
你不能把一条线连在一起Thread.join()等待线程死亡。但是如果你从你想要停止的线程调用它,它只会永远等待
要停止线程,只需从
run()
方法返回即可。在您的情况下,只需在catch子句中添加return
,而不是调用closeThread()
看来你的记忆力有问题。无论你在
exportCorner()
中做什么,都会占用大量内存,或者一次创建多个线程。正如Andy Turner在评论中提到的,使用ExecutorService来处理Runnable
可能是有用的。这可能有助于管理线程并确保有限的线程数