Java多線程捕獲異常的處理方式有以下幾種:
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 執行線程任務
} catch (Exception e) {
// 處理異常
}
}
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<?> future = executorService.submit(new MyRunnable());
try {
future.get();
} catch (Exception e) {
// 處理異常
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 處理未捕獲異常
}
});
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 執行線程任務
} catch (Exception e) {
Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
}
}
}
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 處理未捕獲異常
}
};
Thread thread = new Thread(new MyRunnable());
thread.setUncaughtExceptionHandler(handler);
thread.start();
無論采用哪種處理方式,都可以根據具體需求來選擇適合的處理方式。