2013-08-23 43 views
-1

我如何在Java中每秒提高N個事件?如何在Java中每秒提高N個事件?

基本上我有一個測試工具,想要提升事件/稱爲方法每秒N次。

有人可以幫我弄清楚如何做到這一點?

+0

也許,你可以看看使用線程。 – guisantogui

+0

每秒N個事件表示您必須每隔1/N秒觸發一次事件。看看'Thread.sleep();' –

+0

爲此,最好不要使用Thread和Thread.sleep()。 Timer在這種情況下完全符合要求 –

回答

2

隨着chrylis回答,Timer類可以適合你。 Here我寫的這個答案可以幫助你。

package perso.tests.timer; 

import java.util.Timer; 
import java.util.TimerTask; 

public class TimerExample extends TimerTask{ 

     Timer timer; 
     int executionsPerSecond; 

     public TimerExample(int executionsPerSecond){ 
      this.executionsPerSecond = executionsPerSecond; 
     timer = new Timer(); 
     long period = 1000/executionsPerSecond; 
     timer.schedule(this, 200, period); 
     } 

     public void functionToRepeat(){ 
      System.out.println(executionsPerSecond); 
     } 
     public void run() { 
      functionToRepeat(); 
     } 
     public static void main(String args[]) { 
     System.out.println("About to schedule task."); 
     new TimerExample(3); 
     new TimerExample(6); 
     new TimerExample(9); 
     System.out.println("Tasks scheduled."); 
     } 
}