1当线程的线程体内部无捕获异常,将异常抛出线程体外,不同情况下,程序处理机制
测试类
1 package com.ehking.bankchannel.domesticremit.facade.impl; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.concurrent.Executor; 6 import java.util.concurrent.Executors; 7 8 9 public class ThreadTest { 10 11 private static Executor executor=Executors.newCachedThreadPool(); 12 13 14 public static void main(String[] args) { 15 test01(); 16 //test02(); 17 } 18 19 /** 20 * 线程池,主线程往线程池提交任务(子线程) 21 * 如果任务中有往外抛出异常,主线程并不会捕获异常。 22 * 是线程池捕获了任务的异常 23 */ 24 public static void test02(){ 25 26 ThreadTask aTask=new ThreadTask(1); 27 ThreadTask aTask2=new ThreadTask(2); 28 ThreadTask aTask3=new ThreadTask(6); 29 List<ThreadTask> aList=new ArrayList<ThreadTask>(); 30 aList.add(aTask); 31 aList.add(aTask2); 32 aList.add(aTask3); 33 try { 34 for(ThreadTask a:aList){ 35 executor.execute(a); 36 } 37 System.out.println("ThreadTest.test02(没有执行)"); 38 } catch (Exception e) { 39 System.out.println("ThreadTest.test02()"+e); 40 } 41 42 43 } 44 /** 45 * 如果用匿名线程,匿名线程中有抛出异常,无捕获的话,主线程是会捕获这个异常 46 */ 47 public static void test01(){ 48 System.out.println("ThreadTest.test01()==>主线程运行开始"); 49 final List<String> list=new ArrayList<String>(); 50 try { 51 list.add("sxf"); 52 list.add("chn"); 53 54 Thread thread=new Thread(new Runnable() { 55 56 @Override 57 public void run() { 58 System.out 59 .println("ThreadTest.test01().new Runnable() {...}.run()子线程加爱"); 60 list.add("love"); 61 System.out 62 .println("ThreadTest.test01().new Runnable() {...}.run()子线程抛出异常"); 63 int a=3/0; 64 System.out 65 .println("ThreadTest.test01().new Runnable() {...}.run()z县城结束"); 66 } 67 }); 68 thread.start(); 69 70 71 } catch (Exception e) { 72 System.out.println("ThreadTest.test01()子线程抛出异常"+e); 73 } 74 75 try { 76 Thread.sleep(3000L); 77 } catch (InterruptedException e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } 81 for(String aString:list){ 82 System.out.println("ThreadTest.test01()打印==>"+aString); 83 } 84 System.out.println("ThreadTest.test01()==>主线程运行结束"); 85 } 86 }
View Code
线程类
1 package com.ehking.bankchannel.domesticremit.facade.impl; 2 3 public class ThreadTask implements Runnable{ 4 5 private int a; 6 7 public ThreadTask(int a){ 8 this.a=a; 9 } 10 11 @Override 12 public void run() { 13 if(a%2==0){ 14 System.out.println("ThreadTask.run()【"+a+"】运行正常......."); 15 }else{ 16 System.out.println("ThreadTask.run()【"+a+"】抛出异常"); 17 int s=2/0; 18 } 19 20 } 21 22 23 }
View Code
时间: 2025-01-31 05:43:44