如何在循环内定期运行具有不同参数的方法?
Iteration 1 : obj.process(index1)
wait 5 seconds...
Iteration 2: obj.process(index2)
wait 5 seconds...
Iteration 3: obj.process(index3)
wait 5 seconds...
and so on...
具体来说,我的目标是重复运行一个方法,下一次迭代需要等待X秒,而下一次迭代也需要等待X秒,依此类推。
我的示例代码是错误的,几乎同时启动了所有obj.process(index):
Timer time = new Timer();
for (final String index : indeces) {
int counter = 0;
time.schedule(new TimerTask() {
@Override
public void run() {
indexMap.put(index, obj.process(index));
}
}, delay);
counter++;
if (counter > indeces.size())
System.exit(0);
}
最佳答案
如果您的代码在其自己的线程中运行,则以下最小示例可能会很有用:
public static void main(String[] args) {
Object[][] parameters ={ new String[]{"HELLO", "WORLD"},
new Integer[]{1,2,3},
new Double[]{0.1, 0.9, 5.3}
};
for (int i = 0; i < parameters.length; i++) {
try {
TimeUnit.SECONDS.sleep(1);
doSomething(parameters[i]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void doSomething(Object[] objects) {
System.out.println(Arrays.toString(objects));
}
在Java 8中,可能的解决方案可能是:
public static void main(String[] args) {
Object[][] parameters ={ new String[]{"HELLO", "WORLD"},
new Integer[]{1,2,3},
new Double[]{0.1, 0.9, 5.3}
};
Arrays.stream(parameters).forEachOrdered(p -> doSomething(p));
}
private static void doSomething(Object[] objects) {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(Arrays.toString(objects));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
关于java - 在JAVA的循环中每隔X秒执行一次具有不同参数的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29510902/