在JAVA中,每x秒使用循环中的不同参数执行一个方法
如何在循环中使用不同的参数周期性地运行方法在JAVA中,每x秒使用循环中的不同参数执行一个方法,java,scheduled-tasks,timertask,Java,Scheduled Tasks,Timertask,如何在循环中使用不同的参数周期性地运行方法 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秒,以此类推 我的示例代码是错误的,
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秒,以此类推
我的示例代码是错误的,几乎同时启动所有对象进程(索引):
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);
}
对所有对象使用一个
计时器。使run
方法处理单个对象。如果有更多的对象要处理,请让运行
方法重新安排时间任务
(即此
)
使用这种解决方案,您不需要循环,只需设置一次计时器。这似乎对我有效:
public class TestClass {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String [] indeces = new String[] {"one", "two", "three"};
long delay = 0;
Timer time = new Timer();
for (final String index : indeces) {
int counter = 0;
System.out.println("index-->" + delay);
time.schedule(new TimerTask() {
Map indexMap = new HashMap();
@Override
public void run() {
indexMap.put(index, index);
System.out.println("index-->" + index);
}
}, delay);
counter++;
delay = delay + 5000; // Increase delay by 5 secs
if (counter > indeces.length)
System.exit(0);
}
}
基本上,我已经将每个计时器任务的延迟增加了5秒如果代码在自己的线程中运行,下面的最小示例可能会很有用:
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));
}
因此,假设要迭代一个循环10次,每次都要传递不同的参数并等待几秒钟。这是你想要的吗??
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();
}
}