(转载)线程定时执行的两种实现方法

来源:互联网 发布:linux 重新安装lnmp 编辑:程序博客网 时间:2024/06/05 05:59
package test;
 
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
 
public class TimerTest {
    public static void main(String[] args){    
        long now = System.currentTimeMillis();
         
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        System.out.println("当前系统时间:" + df.format(new Date()));// new Date()为获取当前系统时间
        System.out.println("当前系统时间2: " + transferLongToDate("yyyy-MM-dd HH:mm:ss", now));
         
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 55);
        calendar.set(Calendar.SECOND, 0);
 
        long specTime = calendar.getTimeInMillis();
        <br>    //方法一: 使用线程的sleep方法,让线程休眠来达到按时执行的效果
        MyThread thread = new MyThread();
        try {
            Thread.sleep(specTime - now);
            thread.start();
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    <br>    //方法二: 使用timer.schedule来实现定时执行线程,参数按如下方法执行即可
        /*Timer timer = new Timer();    
        timer.schedule(new MyTask(), specTime - now, 2000);//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.    
         */
    }   
    // 使用内部类,来实现线程执行后,每隔两秒继续执行一次
    static class MyThread extends Thread{
        public void run(){
            System.out.println("________");
            MyThread thread = new MyThread();
            try {
                Thread.sleep(2000);
                thread.start();
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
     
      //使用内部类,利用TimerTask来实现线程的定时执行
    static class MyTimerTask extends java.util.TimerTask{     
        public void run(){    
            System.out.println("________");    
        }    
    }  
     
    /**
     * 把毫秒转化成日期
     * @param dateFormat(日期格式,例如:MM/ dd/yyyy HH:mm:ss)
     * @param millSec(毫秒数)
     * @return
     */
    public static String transferLongToDate ( String dateFormat, long millSec )
    {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date = new Date(millSec);
        return sdf.format(date);
    }
}

原创粉丝点击