我正在使用线程,并决定使用最现代的API (java.util)。concurrent包).
下面是我想做的(伪代码):
//List of threads
private ScheduledExecutorService checkIns = Executors.newScheduledThreadPool(10);
//Runnable class
private class TestThread implements Runnable{
private int index = 0;
private long startTime = 0;
private long timeToExecute = 3000000;
public TestThread(int index){
this.index = index;
}
public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
else if(startTime > (startTime+timeToExecute))
//End Thread
System.out.println("Execute thread with index->"+index);
}
}
//Cycle to create 3 threads
for(int i=0;i< 3; i++)
checkIns.scheduleWithFixedDelay(new TestThread(i+1),1, 3, TimeUnit.SECONDS);
我想在某个日期运行一个任务,并重复它直到一定的时间。时间过去后,任务结束。我唯一的问题是如何结束这条线?
当任务不应该再执行时,您可以抛出异常,但这是相当残酷的。
- 调度任务一次,使任务意识到调度程序,因此它可以在完成当前迭代时重新调度自己-但如果它在最终时间之后立即返回。
- 使用像Quartz Scheduler这样的东西,它更适合这种事情。
当然,第一个版本可以被封装成一种更令人愉快的形式——您可以创建一个"SchedulingRunnable",它知道何时运行子任务(提供给它)以及运行多长时间。
当run
方法存在时线程终止。似乎你只需要做以下事情:
public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < (startTime+timeToExecute)){
// do work here
}
//End Thread
System.out.println("Execute thread with index->"+index);
}
如果你想做一个连续的任务:在run函数中创建一个while循环,它会时不时地检查它是否已经运行了足够长的时间。当任务完成时(run()函数退出),线程可以自由地用于其他任务。使用日程安排器来安排每天重复的任务。
如果你不想要一个连续的任务,你有几个选择。我想说的一个简单的方法是,如果你想安排一个新的一次性任务,决定何时完成部分任务。