Java 执行具有时间间隔的可运行项列表
我有个问题要解决。在其中,我需要在每次请求执行中都有一些延迟的情况下运行可运行对象列表 比如说,我有一个如下的清单Java 执行具有时间间隔的可运行项列表,java,multithreading,Java,Multithreading,我有个问题要解决。在其中,我需要在每次请求执行中都有一些延迟的情况下运行可运行对象列表 比如说,我有一个如下的清单 List<MyReqObject> myReqObjects=new ArrayList<MyReqObject>(); ExecutorService execute=Executors.newFixedThreadPool(X) 现在使用execute.invokeAl(myReqObjects)我试图调用所有这些请求 但我应该在这两者之间有一个延迟
List<MyReqObject> myReqObjects=new ArrayList<MyReqObject>();
ExecutorService execute=Executors.newFixedThreadPool(X)
现在使用execute.invokeAl(myReqObjects)代码>我试图调用所有这些请求
但我应该在这两者之间有一个延迟。
为了做到这一点,我尝试了
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS);
但在这里我不能发送列表作为参数,所以我可以执行相同的请求7秒,延迟2秒
有没有办法解决我的问题请建议我创建一个计时器:
Timer timer = new Timer();
如果需要运行一次,则:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your code here
}
}, 2*1000);
要重复运行:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your code here
}
}, 2*1000);
请参阅计时器和TimerTask的一些编码示例,您可以制作一个Runnable,它是可运行列表的包装,并跟踪发送的内容。然后将单个Runnable作为调度程序的对象
public class RunnableList implements Runnable {
private List<Runnable> runList = Collections.synchronizedList(
new ArrayList<Runnable>());
public void addRunnable(Runnable r) {
runList.add(r);
}
@Override
public void run() {
if(!runList.isEmpty()) {
runList.remove(0).run();
}
}
}
公共类RunnableList实现Runnable{
私有列表runList=Collections.synchronizedList(
新的ArrayList());
public void addRunnable(Runnable r){
添加(r);
}
@凌驾
公开募捐{
如果(!runList.isEmpty()){
runList.remove(0.run();
}
}
}
本质上是一个本身是可运行的集合对象。请注意,如果您选择Executor路线,您将对Callable执行类似的操作。一个问题。这些可运行程序是否需要在其上一个可运行程序完成后N秒或在计划上一个可运行程序后N秒执行
如果是后者,则可以连续计划和增加时间计数器
int timeToWait = 2000;
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS);
for(int i = 1; i <= runnables.size(); i++){
scheduler.schedule(r, timeToWait * i, TimeUnit.MILLISECONDS);
}
int timeToWait=2000;
ScheduledExecutorService scheduler=执行者。newScheduledThreadPool(1);
scheduleAtFixedRate(myObject,2,7,秒);
对于(inti=1;i),您可以在可运行文件列表中循环以独立提交每个可运行文件。
final int timeToWait = 2000;
class SchedulingRunnable implements Runnable{
private final Iterator<Runnable> runnables;
private final ScheduledExecutorService scheduler
public SchedulingRunnable(Iterator<Runnable> rs, ScheduledExecutorService es){..}
public void run(){
runnables.next().run(); //assuming runnables.hasNext()
if(runnables.hasNext()){
scheduler.schedule(this, timeToWait, TimeUnit.MILLISECONDS);
}
}
}
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.schedule(new SchedulingRunnable(runnables.iterator(),schedule), timeToWait, TimeUnit.MILLISECONDS);