线程池异常捕获

捕获线程池的异常方法分为两种

1、一种是使用Thread和Runnable启动的线程使用UncaughtExceptionHandler

2、第二种是使用Callable和Future启动的现场,根据Future.get()捕获异常

第一种

首先创建一个线程运行类

package test.thread.ex;

import java.util.concurrent.CountDownLatch;

public class MyThread3 implements Runnable {
	private int count ;
	private CountDownLatch countDownLatch;
	
	public MyThread3(int count,CountDownLatch countDownLatch) {
		this.count = count;
		this.countDownLatch = countDownLatch;
	}

	@Override
	public void run() {
		countDownLatch.countDown();
		if(count == 0){
			System.out.println("count == 0");
		}else{
			throw new RuntimeException("throws exception");
		}
	}
}

然后运行线程捕获异常

package test.thread.ex;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoTest3 {
	//设置主线程可以运行的变量标志位
	private static boolean flag = true;
	private static CountDownLatch countDownLatch = new CountDownLatch(2);
	
	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				flag = false;
				e.printStackTrace();
			}
		});
		
		ExecutorService e = Executors.newFixedThreadPool(2);
		MyThread3 my = new MyThread3(0,countDownLatch);
		MyThread3 my2 = new MyThread3(1,countDownLatch);
		e.execute(my);
		e.execute(my2);
		e.shutdown();
		
		try {
			countDownLatch.await();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		if(flag){
			System.out.println("run success");
		}else{
			System.out.println("run fail");
		}
	}
}

第二种

首先创建一个线程运行类

package test.thread.ex;

import java.util.concurrent.Callable;

public class MyThread2 implements Callable<Integer>{
	@Override
	public Integer call() throws Exception {
		try {
			return 1/0;
		} catch (Exception e) {
			throw new RuntimeException("throws Exception");
		}
	}
}

然后捕获异常

package test.thread.ex;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DemoTest2 {
	
	public static void main(String[] args) {
		
		ExecutorService e = Executors.newFixedThreadPool(1);
		MyThread2 my = new MyThread2();
		
		Future<Integer> f = e.submit(my);
		try {
			f.get();
		} catch (InterruptedException | ExecutionException e1) {
			e1.printStackTrace();
		}
	}
}

猜你喜欢

转载自my.oschina.net/u/3239611/blog/1537313