這篇文章主要介紹了詳解Java中多線程異常捕獲Runnable的實現的相關資料,希望透過本文能幫助到大家,讓大家理解掌握這樣的知識,需要的朋友可以參考下
詳解Java中多執行緒異常捕捉Runnable的實作
1、背景:
Java 多執行緒異常不向主執行緒拋,自己處理,外部捕獲不了異常。所以要實現主線程對子線程異常的捕獲。
2、工具:
實作Runnable介面的LayerInitTask類,ThreadException類,執行緒安全的Vector
3、想法:
#
package step5.exception; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.autonavi.pds.core.incre.impl.LayerInitTask; public class ThreadException { public static void main(String[] args) { try { Vector<String> errRet = new Vector(); ExecutorService pool = Executors.newFixedThreadPool(6); for (int i = 0; i < 6; ++i) { pool.execute(new LayerInitTask(i, errRet)); } pool.shutdown(); pool.awaitTermination(1, TimeUnit.DAYS); if (errRet.size() > 0) { System.out.println("根据返回值捕获:exception"); throw new RuntimeException( "入库失败!"); } } catch (Exception e) { System.out.println("根据抛出异常捕获:exception"); throw new RuntimeException( "入库失败!"); } System.out.println("-----入库成功,发成功完成工作邮件--------"); } }
package step5.exception; import java.util.Vector; public class LayerInitTask implements Runnable { private int threadNum; private Vector<String> errRet; public LayerInitTask(int num, Vector<String> errRet) { this.threadNum = num; this.errRet = errRet; } @Override public void run() { try { if (this.threadNum == 3) { throw new RuntimeException( this.threadNum + ":数据格式有误."); } System.out.println(this.threadNum + ":刷表成功"); } catch (Exception e) { this.errRet.add("线程:" + this.threadNum + "运行异常!"); throw new RuntimeException( this.threadNum + ":刷表失败"); } } }5、結果:
Exception in thread "pool-1-thread-4" java.lang.RuntimeException: 3:刷表失败 at step5.exception.LayerInitTask.run(LayerInitTask.java:23) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Exception in thread "main" java.lang.RuntimeException: 入库失败! at step5.exception.ThreadException.main(ThreadException.java:27) 2:刷表成功 1:刷表成功 5:刷表成功 0:刷表成功 4:刷表成功 根据返回值捕获:exception 根据抛出异常捕获:exception
以上是Java實作多執行緒異常捕捉Runnable的案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!