2012-11-14 35 views
0

我需要创建一个对象,使用它自己的类方法停止执行一定的时间。如何让程序跟踪时间流逝并在指定的时间过去后执行功能。跟踪currentTimeMillis

我想象.......

long pause; //a variable storing pause length in milliseconds............. 
long currentTime; // which store the time of execution of the pause ,............. 

和当另一个变量跟踪时间具有相同的值作为currentTime的+暂停,则执行代码的下一行。是否有可能创建一个短时间内每变化一个毫秒的变量?

+0

'Thread.sleep(pause)'...? – MadProgrammer

+0

我不能使用任何线程:\分配 –

+1

如何计时器? –

回答

2

对于一个简单的解决方案,你可以只使用Thread#sleep

public void waitForExecution(long pause) throws InterruptedException { 
    // Perform some actions... 
    Thread.sleep(pause); 
    // Perform next set of actions 
} 

具有定时...

public class TimerTest { 

    public static void main(String[] args) { 
     Timer timer = new Timer("Happy", false); 
     timer.schedule(new TimerTask() { 

      @Override 
      public void run() { 
       System.out.println("Hello, I'm from the future!"); 
      } 
     }, 5000); 

     System.out.println("Hello, I'm from the present"); 
    } 
} 

并配有循环

long startAt = System.currentTimeMillis(); 
long pause = 5000; 
System.out.println(DateFormat.getTimeInstance().format(new Date())); 
while ((startAt + pause) > System.currentTimeMillis()) { 
    // Waiting... 
} 
System.out.println(DateFormat.getTimeInstance().format(new Date())); 

注意,这是更那么随着循环继续消耗CPU周期,其他两种解决方案的代价就会很高,其中就是这样和Timer使用内部调度机制,允许线程空闲(并且不消耗周期)

+0

eugh,我知道他想要for循环。我会测试n小提琴,非常感谢你的方向@MadProgrammer :) –

+0

你可能在'while'循环中很好,并调用'Thread#yield',这至少会让系统中的其他线程有机会运行,但是这可能会影响你想要达到的目标 – MadProgrammer