我们说我有一个整数数组
int timeouts [] = {1000 , 2000 , 3000 , 3500};
我想创建一个计时器,计数最多3.5秒,如果毫秒计数等于数组的一个元素,则调用相同的函数。有没有办法在不制作多个计时器的情况下很快完成这项工作?
答案 0 :(得分:1)
public class ArraysFun{
private static int[] timeouts = {1000,2000,3000,3500};
public static void main(String[] sss){
endlessCounter(0);
}
//Endless counter that calls your function
public static void endlessCounter(int i){
long start = System.currentTimeMillis();
long now;
do{
now = System.currentTimeMillis();
//checks to see if the time was elapsed
}while(now - start<timeouts[i]);
//call your function
callFunction(i);
//iterate through the timeouts array
i = (i>= timeouts.length-1)? 0 : i+1;
//call the counter again
endlessCounter(i);
}
//just print which is the timeout that was waited before this call
private static void callFunction(int i) {
double duration = (double)timeouts[i]/1000.00;
System.out.println("Function called after "+ duration + " seconds");
}
}
答案 1 :(得分:0)
对常规java.awt.Timer
进行子类化。
public class VariableTimer extends Timer{
private int [] millis;
private counter = 0;
public VariableTimer(int[] millis, ActionListener l) {
super(millis[0], l);
this.millis = millis;
}
@Override
protected void fireActionPerformed(ActionEvent e) {
super.fireActionPerformed(e);
setDelay(millis[++counter%millis.length]);
restart();
}
}
没有测试过,希望它有效。
答案 2 :(得分:0)
public class Timer {
static final int timeouts [] = {1000 , 2000 , 3000 , 3500};
private static int findMax(int [] array) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
private static void checkIfContained(double number) {
for (int i : timeouts) {
if ((double) i == number) {
System.out.println("SUCCESS!");
// TODO
}
}
}
public static void main(String[] args) throws InterruptedException {
int max = findMax(timeouts);
double counter = 0.0;
while (counter < max) {
Thread.sleep(3500);
counter += 3.5;
checkIfContained(counter);
}
}
}