• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java实现多线程异常捕获Runnable的案例

java 搞代码 4年前 (2022-01-09) 58次浏览 已收录 0个评论

这篇文章主要介绍了详解Java中多线程异常捕获Runnable的实现的相关资料,希望通过本文能帮助到大家,让大家理解掌握这样的知识,需要的朋友可以参考下

详解Java中多线程异常捕获Runnable的实现

1、背景:

Java 多线程异常不向主线程抛,自己处理,外部捕获不了异常。所以要实现主线程对子线程异常的捕获。
2、工具:

实现Runnable接口的LayerInitTask类,ThreadException类,线程安全的Vector
3、思路:

向LayerInitTask中传入Vector,记录异常情况,外部遍历,判断,抛出异常。

4、代码:

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><p>本文来源gao!%daima.com搞$代*!码9网(</p> 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的案例的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java实现多线程异常捕获Runnable的案例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址