守护线程(后台线程)
- 在java语言中线程分为ldalei
- 用户线程和守护线程(后台线程)其中守护线程代表有垃圾回收线程
- 守护线程的特点
- 一般守护线程是一个死循环,所有的用户线程结束,守护线程就结束(main方法也是一个用户线程)
*守护线程的用处 - 假设每天00:00时候系统数据自动备份
- 这个时候就需要设置定时器,并且可以将定时器设置为守护线程
定时器 - 定时器的作用是间隔特定的时间,执行特定的程序
- 在Java的类库中已经写好了一个定时器:java.utll.Timer
定时器的写法
public class TimerTest {
public static void main(String[] args) throws ParseException {
//创建定时器
Timer timer =new Timer();
//守护线程的方式
//Timer timer1 =new Timer(true);
//定时任务,多久执行一次
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fistTime =sdf.parse("2020-12-09 15:50:30");
timer.schedule(new LogTimerTask(),fistTime,1000*10);
}
}
//定时任务类
class LogTimerTask extends TimerTask{
public void run() {
//需要执行的任务
SimpleDateFormat sdf =new SimpleDateFormat();
String strTime = sdf.format( new Date());
System.out.println(strTime + "成功备份一次数据");
}
}
守护线程的写法
public class ThreadTese06 {
public static void main(String[] args) {
Thread t =new BakDataThread();
t.setName("数据备份线程");
//启动守护线程
t.setDaemon(true);
t.start();
//主线程
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class BakDataThread extends Thread{
@Override
public void run() {
int i=0;
while (true){
System.out.println();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}