Java多线程中Timer定时器执行完任务为什么不停止?
public Timer(String name) {
thread.setName(name);
thread.start();
}
这是Timer类中调用的构造方法,那我自己写一个简单的线程程序时,run方法运行结束就停止了,为什么这个定时器中的方法运行完以后却不停止呢?
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("MyThread");
}
}
public class MyThreadTest {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
System.out.println("运行结束");
}
}
public class MyTask extends TimerTask{
@Override
public void run() {
System.out.println("任务执行了,时间为:"+new Date());
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("当前时间为:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND,calendar.get(Calendar.SECOND)-10);
Date runDate = calendar.getTime();
System.out.println("计划时间为:"+runDate);
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task,runDate);
}
}
谢谢指点一下是什么原因?
定时器内部是开启了一个线程去执行任务的,虽然任务执行完成了,但是该线程并没有销毁。
这和自己定义一个线程执行完成 run 方法后就自动销毁是不一样的,Timer 本质上是相当于线程池,它缓存了一个工作线程,一旦任务执行完成,该工作线程就处于空闲状态,等待下一轮任务。
调用下timer.cancel();
https://blog.csdn.net/mars_idea/article/details/80724825