面试-线程中异常解决策略

线程中异常解决策略有三大类

  • 利用在Thread内的run方法中自行处理
  • 为Thread对象设置异常处理Handler(UncaughtExceptionHandler)
  • 获取Future对象
    • 利用FutureTask
    • 利用CompletableFuture
    • 利用CompletableFuture
    • 利用线程池的sumbit进行提交,从而获取Future对象
    • 等等
package com.study;

import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class MultiThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 线程中异常解决策略有三大类:
         * 1、利用在Thread内的run方法中自行处理
         * 2、为Thread对象设置异常处理Handler(UncaughtExceptionHandler)
         * 3、获取Future对象
         *  3.1:利用FutureTask
         *  3.2:利用CompletableFuture
         *  3.3:利用线程池的sumbit进行提交,从而获取Future对象
         *  3.4:等等
         */
    }

    // 根据线程工厂或者thread来捕获异常
    public static void getDataByUncaughtExceptionHandler() {
        // 利用thread中的异常处理handler
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException("你好");
            }
        });
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
            }
        });

        // 或者融合ThreadFatory 线程工厂来做
        ThreadFactory factory = r -> {
            Thread thread1 = new Thread(r);
            thread1.setUncaughtExceptionHandler((t, e) -> System.out.println("记录"));
            thread1.start();
            return thread1;
        };
        factory.newThread(() -> {
            throw new RuntimeException("报错");
        });
    }

    // 利用FutureTask和Callable实现数据返回
    public static void getDataByFuture() throws ExecutionException, InterruptedException {
        FutureTask<Integer> task =new FutureTask<>(() -> {
            Thread.sleep(5000);
            int i = 1/0;
            return 1;
        });
        Thread thread = new Thread(task);
        thread.start();
        // 如果不想影响主线程的继续运行,可以不用throw抛出,而是使用try catch来进行捕获
        System.out.println(task.get());
    }

    // 利用CompletableFuture获取返回值
    public void getDataByCompletableFuture() throws ExecutionException, InterruptedException {

        CompletableFuture future1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("不带返回值");
        });

        // 带有返回值
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return 1;
            }
        }).thenApplyAsync(new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer integer) {
                return integer + 1;
            }
        });
        try {
            System.out.println(future2.get());
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(1); // 子线程报错不会影响主线程继续执行
    }

    public void getDataByExecutor(){
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Future<Integer> submit = pool.submit(() -> {throw new RuntimeException("报错");});
        try {
            submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        pool.shutdown();
        System.out.println(1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值