【福利资源】
【编程电子书大全】https://pan.baidu.com/s/1yhPJ9LmS_z5TdgIgxs9NvQ?pwd=yyds > 提取码: yyds
在 Java 中,如果在 Runnable 的 run() 方法中抛出异常,该异常不会直接影响调用 start() 方法的外层代码。具体来说,Runnable 中的异常会在它所运行的线程中被抛出,而不会传播到启动这个线程的主线程或其他线程。
示例
以下是一个简单的示例,展示了 Runnable 中抛出异常的行为:
public class Main {
public static void main(String[] args) {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread started");
throw new RuntimeException("Exception in thread");
}
};
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println("Main thread continues...");
}
}
在这个示例中,Runnable 的 run() 方法中抛出了一个 RuntimeException。当你运行这个代码时,你会看到以下输出:
Thread started
Main thread continues...
Exception in thread "Thread-0" java.lang.RuntimeException: Exception in thread
at Main$1.run(Main.java:8)
at java.base/java.lang.Thread.run(Thread.java:831)
可以看到,异常被打印出来,但主线程(即 main 方法)继续执行,并打印出 “Main thread continues…”。
捕获和处理异常
如果你希望捕获和处理 Runnable 中的异常,可以在 run() 方法中使用 try-catch 块。
public class Main {
public static void main(String[] args) {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("Thread started");
throw new RuntimeException("Exception in thread");
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
};
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println("Main thread continues...");
}
}
输出:
Thread started
Caught exception: Exception in thread
Main thread continues...
使用 ExecutorService 和 Future
如果你需要从外层捕获异常,可以考虑使用 ExecutorService 和 Future,并使用 Callable 接口而不是 Runnable。这样你可以从 Future 对象中获取异常。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<Void> callableTask = () -> {
System.out.println("Thread started");
throw new RuntimeException("Exception in thread");
};
Future<Void> future = executorService.submit(callableTask);
try {
future.get(); // 这会等待任务完成,并在发生异常时抛出 ExecutionException
} catch (InterruptedException | ExecutionException e) {
System.out.println("Caught exception: " + e.getCause().getMessage());
} finally {
executorService.shutdown();
}
System.out.println("Main thread continues...");
}
}
输出:
Thread started
Caught exception: Exception in thread
Main thread continues...
在这个示例中,ExecutionException 包装了任务中抛出的异常,你可以通过 getCause() 方法获取原始异常。
总结
- 在
Runnable的run()方法中抛出的异常不会直接影响外层代码。 - 可以在
run()方法中使用try-catch块来捕获和处理异常。 - 如果需要从外层捕获异常,可以使用
ExecutorService和Callable,并通过Future对象获取异常。
通过这些方法,你可以更灵活地处理多线程编程中的异常情况。



















