1.jdk自带的Timer
public class Timer{
static int index=0;
public static void main(String[] args){
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
index++;
System.out.println("你好");
if (index>100){
timer.cancel();
}
}
},0,1000);
}
}
2.线程方式
public class ThreadTest implements Runnable{
static int i=0;
@Override
public void run() {
Boolean t=true;
while (t){
i++;
try {
if (i<100) {
Thread.sleep(1000);
System.out.println("你好");
}else{
t=false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
ThreadTest test=new ThreadTest();
Thread t=new Thread(test);
t.start();
}
3.推荐使用spring的@Scheduled注解定时(这个注解还有很多方式)
1 @Scheduled(cron="0 0 8 * * ?")
2 public void note(){
3 System.out.println("你好");
4 }