Timer 的学习
Timer 实例化多个对象就会启动多个线程
TimerTask 中 捕获异常为基类Exception,那么出现异常后就继续执行.及时报错
TimerTask中未捕获异常或者捕获异常与程序抛出异常不一致,都会导致当前线程停止。
TaskTEST1.java :不捕获异常 package TaskTestPackage; import java.util.TimerTask; public class TaskTEST1 extends TimerTask{ boolean bool=true; int i=0; @Override public void run() throws ArrayIndexOutOfBoundsException{ i=i+1; if (i>5) { throw new RuntimeException(); }else { System.out.println(i); } } } TaskTEST2.java package TaskTestPackage; import java.util.TimerTask; public class TaskTEST2 extends TimerTask{ int a=999999; @Override public void run() { // TODO Auto-generated method stub a=a-10; System.out.println(a); } } ETL.java package TaskTestPackage; import java.util.Date; import java.util.Timer; public class ETL { public static void main(String[] args) { Timer timer=new Timer(); timer.schedule(new TaskTEST1(), new Date(), 1000); Timer timer1=new Timer(); timer1.schedule(new TaskTEST2(), new Date(), 1000); } } 执行结果:
修改TaskTEST1.java:捕获异常为Exception 基类 package TaskTestPackage; import java.util.TimerTask; public class TaskTEST1 extends TimerTask{ boolean bool=true; int i=0; @Override public void run() throws ArrayIndexOutOfBoundsException{ try { i=i+1; if (i>5) { throw new RuntimeException(); }else { System.out.println(i); } }catch(Exception ex){ System.out.println(ex); } } } 执行结果如下
修改TaskTEST1.java:捕获异常与抛出异常不一致 package TaskTestPackage; import java.util.TimerTask; public class TaskTEST1 extends TimerTask{ boolean bool=true; int i=0; @Override public void run() throws ArrayIndexOutOfBoundsException{ try { i=i+1; if (i>5) { throw new RuntimeException(); }else { System.out.println(i); } }catch(ArrayIndexOutOfBoundsException ex){ System.out.println(ex); } } } 执行结果: