java的Runnable里面抛异常怎么办?

【福利资源】

【编程电子书大全】https://pan.baidu.com/s/1yhPJ9LmS_z5TdgIgxs9NvQ?pwd=yyds > 提取码: yyds

在 Java 中,如果在 Runnablerun() 方法中抛出异常,该异常不会直接影响调用 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...");
    }
}

在这个示例中,Runnablerun() 方法中抛出了一个 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

如果你需要从外层捕获异常,可以考虑使用 ExecutorServiceFuture,并使用 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() 方法获取原始异常。

总结

  • Runnablerun() 方法中抛出的异常不会直接影响外层代码。
  • 可以在 run() 方法中使用 try-catch 块来捕获和处理异常。
  • 如果需要从外层捕获异常,可以使用 ExecutorServiceCallable,并通过 Future 对象获取异常。

通过这些方法,你可以更灵活地处理多线程编程中的异常情况。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值