Java TimerTask example

Rahul

New Member
#1
I need to execute a thread at a regular interval of time. I am using timerTask method in my java program
Mã:
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
 

Admin

Administrator
Thành viên BQT
#2
The Java Virtual Machine exits when the only threads running are all daemon threads.

So change to

Mã:
Timer timer = new Timer();
This will create a user Thread
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top