java子线程出现异常主线程获取异常并终止程序执行返回错误码?用线程池实现 Systemexit1;可能让我整个web应用停止我只希望该线程的池的任务停止
可以通过设置一个全局变量来控制主线程是否终止程序的执行。当子线程出现异常时,将该全局变量设置为true,然后在主线程中判断该变量的值,如果为true,则调用System.exit(1)来终止程序的执行。
具体实现如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainThreadTerminationExample {
private static volatile boolean shouldTerminate = false;
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
try {
// 子线程的任务代码
// ...
// 如果出现异常,设置shouldTerminate为true
throw new RuntimeException("Exception occurred in sub-thread");
} catch (Exception e) {
shouldTerminate = true;
}
});
// 在主线程中判断shouldTerminate的值
if (shouldTerminate) {
System.exit(1);
}
}
}
在上述代码中,使用了一个线程池来执行子线程的任务。当子线程出现异常时,将shouldTerminate设置为true。在主线程中判断shouldTerminate的值,如果为true,则调用System.exit(1)来终止程序的执行。
需要注意的是,为了确保shouldTerminate的可见性,需要使用volatile关键字进行修饰。这样可以保证不同线程对该变量的修改对其他线程是可见的
原文地址: https://www.cveoy.top/t/topic/ivWW 著作权归作者所有。请勿转载和采集!