線程異常?
線程出現(xiàn)異常測(cè)試
任務(wù)類:Task.javapublic class Task implements Runnable {private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
if (i == 5) {
//System.out.println("throw exception");
throw new IllegalArgumentException();
}
System.out.println(i);
}
}
如果i==5,將拋出一個(gè)異常
線程測(cè)試類:TaskTest.javapublic class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
try {
new Thread(new Task(i++)).start();
} catch (Exception e) {
System.out.println("catch exception...");
}
}
}
}
通過使用try-catch,嘗試對(duì)拋出的異常進(jìn)行捕獲
測(cè)試結(jié)果Connected to the target VM, address: '127.0.0.1:64551', transport: 'socket'
0
1
2
3
4
6
7
8
9
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException
at com.h2t.study.thread.Task.run(Task.java:21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
異常沒有被捕獲,只是在控制臺(tái)打印了異常,并且不影響后續(xù)任務(wù)的執(zhí)行 emmmm這是為什么呢,捕獲不到異常就不知道程序出錯(cuò)了,到時(shí)候哪天有個(gè)任務(wù)不正常排查都排查不到,這樣是要不得的。看一下Thread這個(gè)類,有個(gè)叫dispatchUncaughtException的方法,作用如其名,分發(fā)未捕獲的異常,把這段代碼揪出來:Thread#dispatchUncaughtException
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
find usage是找不到該方法在哪里調(diào)用的,因?yàn)檫@個(gè)方法只被JVM調(diào)用 Thread#getUncaughtExceptionHandler: 獲取UncaughtExceptionHandler接口實(shí)現(xiàn)類
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
UncaughtExceptionHandler是Thread中定義的接口,在Thread類中uncaughtExceptionHandler默認(rèn)是null,因此該方法將返回group,即實(shí)現(xiàn)了UncaughtExceptionHandler接口的ThreadGroup類 UncaughtExceptionHandler#uncaughtException: ThreadGroup類的uncaughtException方法實(shí)現(xiàn)
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
因?yàn)樵赥hread類中沒有對(duì)group【parent】和defaultUncaughtExceptionHandler【Thread.getDefaultUncaughtExceptionHandler】進(jìn)行賦值,因此將進(jìn)入最后一層條件,將異常打印到控制臺(tái)中,對(duì)異常不做任何處理。 整個(gè)異常處理器調(diào)用鏈如下:
首先判斷默認(rèn)異常處理器【defaultUncaughtExceptionHandler】是不是為null,在判斷線程組異常處理器【group】是不是為null,在判斷自定義異常處理器【uncaughtExceptionHandler】是不是為null,都為null則在控制臺(tái)打印異常
線程異常處理分析了一下源碼就知道如果想對(duì)任務(wù)執(zhí)行過程中的異常進(jìn)行處理一個(gè)就是讓ThreadGroup不為null,另外一種思路就是讓UncaughtExceptionHandler類型的變量值不為null。
異常處理器:ExceptionHandler.javaprivate static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("異常捕獲到了:" + e);
}
}
設(shè)置默認(rèn)異常處理器Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("異常捕獲到 了: " + e));
int i = 0;
while (true) {
if (i == 10) break;
Thread thread = new Thread(new Task(i++));
thread.start();
}
打印結(jié)果:
0
2
1
3
9
6
7
4
異常捕獲到了:java.lang.IllegalArgumentException
8
通過設(shè)置默認(rèn)異常就不需要為每個(gè)線程都設(shè)置一次了
設(shè)置自定義異常處理器Thread t = new Thread(new Task(i++));
t.setUncaughtExceptionHandler(new ExceptionHandler());
打印結(jié)果:
0
2
4
異常捕獲到了:java.lang.IllegalArgumentException
6
1
3
7
9
8
設(shè)置線程組異常處理器MyThreadGroup myThreadGroup = new MyThreadGroup("測(cè)試線程線程組");
Thread t = new Thread(myThreadGroup, new Task(i++))
自定義線程組:MyThreadGroup.java
private static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕獲到異常了:" + e);
}
}
打印結(jié)果:
1
2
0
4
3
6
7
8
9
捕獲到異常了:java.lang.IllegalArgumentException
線程組異常捕獲處理器很適合為線程進(jìn)行分組處理的場(chǎng)景,每個(gè)分組出現(xiàn)異常的處理方式不相同 設(shè)置完異常處理器后異常都能被捕獲了,但是不知道為什么設(shè)置異常處理器后任務(wù)的執(zhí)行順序亂了,難道是因?yàn)闉槊總€(gè)線程設(shè)置異常處理器的時(shí)間不同【想不通】
線程池異常處理一般應(yīng)用中線程都是通過線程池創(chuàng)建復(fù)用的,因此對(duì)線程池的異常處理就是為線程池工廠類【ThreadFactory實(shí)現(xiàn)類】生成的線程添加異常處理器
默認(rèn)異常處理器Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new Task(i++))
自定義異常處理器ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.setThreadFactory(new MyThreadFactory());
threadPoolExecutor.execute(new Task(i++));
自定義工廠類:
MyThreadFactory.java
private static class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
//自定義UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new ExceptionHandler());
return t;
}
}
設(shè)計(jì)原則,為什么要由線程自身進(jìn)行捕獲來自JVM的設(shè)計(jì)理念"線程是獨(dú)立執(zhí)行的代碼片斷,線程的問題應(yīng)該由線程自己來解決,而不要委托到外部"。因此在Java中,線程方法的異常【即任務(wù)拋出的異常】,應(yīng)該在線程代碼邊界之內(nèi)處理掉,而不應(yīng)該在線程方法外面由其他線程處理
線程執(zhí)行Callable任務(wù)前面介紹的是線程執(zhí)行Runnable類型任務(wù)的情況,眾所周知,還有一種有返回值的Callable任務(wù)類型 測(cè)試代碼:
TestTask.java
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("異常捕獲到了:" + e);
}
}
}
打印結(jié)果:
Disconnected from the target VM, address: '127.0.0.1:64936', transport: 'socket'
0
1
2
3
4
6
7
8
9
觀察結(jié)果,異常沒有被捕獲,thread.setUncaughtExceptionHandler(new ExceptionHandler())方法設(shè)置無效,emmmmm,這又是為什么呢,在問為什么就是十萬個(gè)為什么兒童了。查看FutureTask的run方法,F(xiàn)utureTask#run:
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);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
FutureTask#setException:
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將異常設(shè)置給outcome變量
outcome = t;
//設(shè)置任務(wù)的狀態(tài)為EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
看到catch這段代碼,當(dāng)執(zhí)行任務(wù)捕獲到異常的時(shí)候,會(huì)將任務(wù)的處理結(jié)果設(shè)置為null,并且調(diào)用setException方法對(duì)捕獲的異常進(jìn)行處理,因?yàn)閟etUncaughtExceptionHandler只對(duì)未捕獲的異常進(jìn)行處理,F(xiàn)utureTask已經(jīng)對(duì)異常進(jìn)行了捕獲處理,因此調(diào)用setUncaughtExceptionHandler捕獲異常無效 對(duì)任務(wù)的執(zhí)行結(jié)果調(diào)用get方法:
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
//打印結(jié)果
try {
System.out.println(task.get());
} catch (Exception e) {
System.out.println("異常被抓住了, e: " + e);
}
}
執(zhí)行結(jié)果將會(huì)將捕獲到的異常打印出來,執(zhí)行結(jié)果:
0
1
2
3
4
異常被抓住了, e: java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException
6
7
Disconnected from the target VM, address: '127.0.0.1:50900', transport: 'socket'
8
9
FutureTask#get:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//未完成等待任務(wù)執(zhí)行完成
s = awaitDone(false, 0L);
return report(s);
}
FutureTask#report:
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
outcome在setException方法中被設(shè)置為了異常,并且s為state的狀態(tài)最終8被設(shè)置為EXCEPTIONAL,因此方法將捕獲的任務(wù)拋出【new ExecutionException((Throwable)x)】
總結(jié):Callable任務(wù)拋出的異常能在代碼中通過try-catch捕獲到,但是只有調(diào)用get方法后才能捕獲到
【北京】IT技術(shù)人員面對(duì)面試、跳槽、升職等問題,如何快速成長(zhǎng),獲得大廠入門資格和升職加薪的籌碼?與大廠技術(shù)大牛面對(duì)面交流,解答你的疑惑。《從職場(chǎng)小白到技術(shù)總監(jiān)成長(zhǎng)之路:我的職場(chǎng)焦慮與救贖》活動(dòng)鏈接:http://mk1.top/1ndjnvb想了解更多Java相關(guān),百度搜索圈T社區(qū)www.aiquanti.com,免費(fèi)視頻教程。純干貨