java多线程中出现了异常,如何捕获。利用UncaughtExceptionHandler这个接口就可以了。
代码如下:
package com.ming.thread.six.threadcreateException; public class MyThread extends Thread{ public void run(){ String uname=null; System.out.println(uname.hashCode()); } }
package com.ming.thread.six.threadcreateException; import java.lang.Thread.UncaughtExceptionHandler; public class Run { public static void main(String[] args) { MyThread t=new MyThread(); t.setName("mythread"); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {//这个就是异常处理的实现,一旦出现异常就执行里面的方法哦 @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("c出现了线程异常哦"); } }); t.start(); } }
下面这个例子是在一个线程组中实现异常捕捉:
package com.ming.thread.six.threadgroupException; public class MyThreadGroup extends ThreadGroup { public MyThreadGroup(String name){ super(name); } @Override public void uncaughtException(Thread t, Throwable e) { super.uncaughtException(t, e); this.interrupt();//打断 } }
package com.ming.thread.six.threadgroupException; public class MyThread extends Thread{ private String num; public MyThread(ThreadGroup group,String name,String num){ super(group,name); this.num=num; } public void run(){ int numInt=Integer.parseInt(num); while(this.isInterrupted()==false){ System.out.println("死循环中:"+Thread.currentThread().getName()); } } }
package com.ming.thread.six.threadgroupException; public class Test { public static void main(String[] args) { MyThreadGroup group=new MyThreadGroup("我的线程组哦"); MyThread [] myThreads=new MyThread[10]; for(int i=0;i<myThreads.length;i++){ myThreads[i]=new MyThread(group,"线程"+(i+1),"1");//正常线程 myThreads[i].start(); } MyThread newThread=new MyThread(group,"报错线程","sa"); newThread.start(); } }
so,I forget it。。。