每个 Timer timer=new Timer(); 每new 一个 timer开启一个线程,一个线程依次执行。 若想Timer1和Timer2 同时执行,分别用不同的Timer 开启。
public class TimerMain {
public static void main(String[] args) {
System.out.println("start==");
/*Timer timer=new Timer();
Timer timer2=new Timer();
timer.schedule(new Timer1(), 1000);
timer2.schedule(new Timer2(), 1000);*/
List list = new ArrayList();
list.add(new Timer1());
list.add(new Timer2());
for (int i = 0; i < list.size(); i++) {
Timer timer3=new Timer();
timer3.schedule((TimerTask) list.get(i), 0, 1000); //0表示 调用TimereTask之后,延迟0秒开始执行run方法
}}
}
public class Timer1 extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("===Timer1 start");
try {
//wait(5000);
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("===Timer1 end");
}
}
public class Timer2 extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("===Timer2");
Thread t1=new Thread(new Timer1());
t1.start();
}
}
运行结果是:
start==
===Timer1 start
===Timer2
===Timer1 start
===Timer1 end //线程休眠10s后
===Timer1 end
public class TimerMain2 {
public static void main(String[] args) {
System.out.println("start==");
Timer timer=new Timer();
timer.schedule(new Timer1(), 1000);
timer.schedule(new Timer2(), 1000);
/*List list = new ArrayList();
list.add(new Timer1());
list.add(new Timer2());
for (int i = 0; i < list.size(); i++) {
Timer timer3=new Timer();
timer3.schedule((TimerTask) list.get(i), 1000);
}*/
}
}
TimerMain2 的运行结果:
start==
===Timer1 start
===Timer1 end //10s后
===Timer1 start
===Timer1 end //线程休眠10s后