简体   繁体   中英

java TimerTask example

I need to execute a thread at a regular interval of time. I am using timerTask method in my java program

public class StudentDTO  extends  TimerTask{
@Override
public void run(){  
    System.out.println("hi");
}
        public static void main(String[] args){ 

    StudentDTO t1=new StudentDTO();  
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(t1, 0, 10000);
    System.out.println("start");

     try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

}

}

when i executed this code,I got answer like

start hi hi

and the program will get terminated. I have to run a thread at each 10 sec.Please suggest me a solution

new Timer(true)更改为new Timer()否则它是一个守护程序线程,并且在主退出时应用程序死亡

The Java Virtual Machine exits when the only threads running are all daemon threads.

So change to

 Timer timer = new Timer();

This will create a user Thread

There are two ways you can make your program run every 10 seconds.

  1. Timer timer=new Timer();
  2. By changing the time you have for thread to sleep. It should be more than or equal to the interval you want to schedule your task.For Instance,

      try { Thread.sleep(12000); } catch (InterruptedException e) { e.printStackTrace(); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM