我正在使用线程,并决定使用最现代的应用程序接口(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);我想在某个日期运行一项任务,并重复该任务直到特定的时间。在时间过去后,任务结束。我唯一的问题是如何以线程结尾?
发布于 2011-09-30 20:19:12
当任务不再执行时,你可以抛出一个异常,但这是一个相当残酷的选择:
当然,第一个版本可以封装成一种更令人愉快的形式--你可以创建一个"SchedulingRunnable“,它知道什么时候运行子任务(提供给它)以及运行多长时间。
发布于 2011-09-30 20:20:47
线程在其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);
}发布于 2011-09-30 20:21:38
如果你想做一个连续的任务:在run函数中,每隔一段时间就执行一次while循环,检查它是否运行了足够长的时间。当任务完成时( run()函数退出),线程就可以自由地用于其他任务了。使用调度程序将任务调度为每天重复执行。
如果你不想要一个连续的任务,你有几个选择。我想说的最简单的方法是,如果你想安排一个新的一次性任务,那就是决定何时完成部分任务。
https://stackoverflow.com/questions/7610160
复制相似问题