专属福利 👉点击领取:651页Java面试题库
public class ThreadPoolException {public static void main(String[] args) {//创建一个线程池ExecutorService executorService= Executors.newFixedThreadPool(1);//当线程池抛出异常后 submit无提示,其他线程继续执行executorService.submit(new task());//当线程池抛出异常后 execute抛出异常,其他线程继续执行新任务executorService.execute(new task());}}//任务类class task implements Runnable{public void run() {System.out.println("进入了task方法!!!");int i=1/0;}}
//当线程池抛出异常后 submit无提示,其他线程继续执行Future<?> submit = executorService.submit(new task());submit.get();
public class ThreadPoolException {public static void main(String[] args) {//创建一个线程池ExecutorService executorService = Executors.newFixedThreadPool(1);//当线程池抛出异常后 submit无提示,其他线程继续执行executorService.submit(new task());//当线程池抛出异常后 execute抛出异常,其他线程继续执行新任务executorService.execute(new task());}}// 任务类class task implements Runnable {public void run() {try {System.out.println("进入了task方法!!!");int i = 1 / 0;} catch (Exception e) {System.out.println("使用了try -catch 捕获异常" + e);}}}
public class ThreadPoolException {public static void main(String[] args) throws InterruptedException {//1.实现一个自己的线程池工厂ThreadFactory factory = (Runnable r) -> {//创建一个线程Thread t = new Thread(r);//给创建的线程设置UncaughtExceptionHandler对象 里面实现异常的默认逻辑t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {System.out.println("线程工厂设置的exceptionHandler" + e.getMessage());});return t;};//2.创建一个自己定义的线程池,使用自己定义的线程工厂ExecutorService executorService = new ThreadPoolExecutor(1,1,0,TimeUnit.MILLISECONDS,new LinkedBlockingQueue(10),factory);// submit无提示executorService.submit(new task());Thread.sleep(1000);System.out.println("==================为检验打印结果,1秒后执行execute方法");// execute 方法被线程工厂factory 的UncaughtExceptionHandler捕捉到异常executorService.execute(new task());}}class task implements Runnable {public void run() {System.out.println("进入了task方法!!!");int i = 1 / 0;}}
Future<?> submit = executorService.submit(new task());//打印异常结果System.out.println(submit.get());
//submit()方法public <T> Future<T> submit(Callable<T> task) {if (task == null) throw new NullPointerException();//execute内部执行这个对象内部的逻辑,然后将结果或者异常 set到这个ftask里面RunnableFuture<T> ftask = newTaskFor(task);// 执行execute方法execute(ftask);//返回这个ftaskreturn ftask;}
public void run() {runWorker(this);}final void runWorker(Worker w) {Thread wt = Thread.currentThread();Runnable task = w.firstTask;w.firstTask = null;w.unlock(); // allow interruptsboolean completedAbruptly = true;try {//这里就是线程可以重用的原因,循环+条件判断,不断从队列中取任务//还有一个问题就是非核心线程的超时删除是怎么解决的//主要就是getTask方法()见下文③while (task != null || (task = getTask()) != null) {w.lock();if ((runStateAtLeast(ctl.get(), STOP) ||(Thread.interrupted() &&runStateAtLeast(ctl.get(), STOP))) &&!wt.isInterrupted())wt.interrupt();try {beforeExecute(wt, task);Throwable thrown = null;try {//执行线程task.run();//异常处理} catch (RuntimeException x) {thrown = x; throw x;} catch (Error x) {thrown = x; throw x;} catch (Throwable x) {thrown = x; throw new Error(x);} finally {//execute的方式可以重写此方法处理异常afterExecute(task, thrown);}} finally {task = null;w.completedTasks++;w.unlock();}}//出现异常时completedAbruptly不会被修改为falsecompletedAbruptly = false;} finally {//如果如果completedAbruptly值为true,则出现异常,则添加新的Worker处理后边的线程processWorkerExit(w, completedAbruptly);}}
public void run() {if (state != NEW ||!UNSAFE.compareAndSwapObject(this, runnerOffset,null, Thread.currentThread()))return;try {Callable<V> c = callable;if (c != null && state == NEW) {V result;boolean ran;try {result = c.call();ran = true;} catch (Throwable ex) {result = null;ran = false;//在此方法中设置了异常信息setException(ex);}if (ran)set(result);}//省略下文。。。。。。setException(ex)`方法如下:将异常对象赋予`outcomeprotected void setException(Throwable t) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {//将异常对象赋予outcome,记住这个outcome,outcome = t;UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final statefinishCompletion();}}
public V get() throws InterruptedException, ExecutionException {int s = state;if (s <= COMPLETING)s = awaitDone(false, 0L);//注意这个方法return report(s);}
private V report(int s) throws ExecutionException {//设置`outcome`Object x = outcome;if (s == NORMAL)//返回`outcome`return (V)x;if (s >= CANCELLED)throw new CancellationException();throw new ExecutionException((Throwable)x);}
final void runWorker(Worker w) {//当前线程Thread wt = Thread.currentThread();//我们的提交的任务Runnable task = w.firstTask;w.firstTask = null;w.unlock(); // allow interruptsboolean completedAbruptly = true;try {while (task != null || (task = getTask()) != null) {w.lock();if ((runStateAtLeast(ctl.get(), STOP) ||(Thread.interrupted() &&runStateAtLeast(ctl.get(), STOP))) &&!wt.isInterrupted())wt.interrupt();try {beforeExecute(wt, task);Throwable thrown = null;try {//直接就调用了task的run方法task.run(); //如果是futuretask的run,里面是吞掉了异常,不会有异常抛出,// 因此Throwable thrown = null; 也不会进入到catch里面} catch (RuntimeException x) {thrown = x; throw x;} catch (Error x) {thrown = x; throw x;} catch (Throwable x) {thrown = x; throw new Error(x);} finally {//调用线程池的afterExecute方法 传入了task和异常afterExecute(task, thrown);}} finally {task = null;w.completedTasks++;w.unlock();}}completedAbruptly = false;} finally {processWorkerExit(w, completedAbruptly);}}
public class ThreadPoolException3 {public static void main(String[] args) throws InterruptedException, ExecutionException {//1.创建一个自己定义的线程池ExecutorService executorService = new ThreadPoolExecutor(2,3,0,TimeUnit.MILLISECONDS,new LinkedBlockingQueue(10)) {//重写afterExecute方法protected void afterExecute(Runnable r, Throwable t) {System.out.println("afterExecute里面获取到异常信息,处理异常" + t.getMessage());}};//当线程池抛出异常后 executeexecutorService.execute(new task());}}class task3 implements Runnable {public void run() {System.out.println("进入了task方法!!!");int i = 1 / 0;}}
public class ThreadPoolException3 {public static void main(String[] args) throws InterruptedException, ExecutionException {//1.创建一个自己定义的线程池ExecutorService executorService = new ThreadPoolExecutor(2,3,0,TimeUnit.MILLISECONDS,new LinkedBlockingQueue(10)) {//重写afterExecute方法protected void afterExecute(Runnable r, Throwable t) {//这个是excute提交的时候if (t != null) {System.out.println("afterExecute里面获取到excute提交的异常信息,处理异常" + t.getMessage());}//如果r的实际类型是FutureTask 那么是submit提交的,所以可以在里面get到异常if (r instanceof FutureTask) {try {Future<?> future = (Future<?>) r;//get获取异常future.get();} catch (Exception e) {System.out.println("afterExecute里面获取到submit提交的异常信息,处理异常" + e);}}}};//当线程池抛出异常后 executeexecutorService.execute(new task());//当线程池抛出异常后 submitexecutorService.submit(new task());}}class task3 implements Runnable {public void run() {System.out.println("进入了task方法!!!");int i = 1 / 0;}}
可以看到使用重写afterExecute这种方式,既可以处理execute抛出的异常,也可以处理submit抛出的异常。