質問

Hi everybody . I developed following code. The purpose is : Printing the current time every 500 ms on the screen . This should take place inside a thread . my code doesn't work and I don't know why.

====================================================================

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimer implements Runnable 
     {
      public class PrintingTask extends TimerTask
      {
           public void run()
           {
                Date CurrentTime = new Date() ; 
                System.out.println(CurrentTime) ; 
            }
       } 
      public void run()
      {
         Timer timer = new  Timer() ; 
         PrintingTask Task1 = new PrintingTask() ; 
         timer.schedule(Task1,500);
       }
      }
  //====================End of the thread : MyTimer========================
    public class Test {
       public static void main(String[] args) throws InterruptedException {
       Thread TimerOfScreen = new Thread(new MyTimer());
       TimerOfScreen.start(); 
                      }

  ======================End of the test class=====================

The Date is printed only once,not every 500ms. any body can fix this code , "without big change in logic" ?

役に立ちましたか?

解決

You are using the version of Timer.schedule() that only runs a task once: Timer.schedule(TimerTask, long), after the specified delay.

You need to specify one of the versions that actually repeats the task: either Timer.schedule(TimerTask, long, long) or Timer.scheduleAtFixedRate(TimerTask, long, long). In both of these, the third argument determines how much time will pass between each execution. The difference is that scheduleAtFixedRate will try to keep the beginning of each task invocation at a nearly constant period from the start time, while schedule will maintain a fairly constant gap between the end of one execution and the beginning of the other.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top