我正在使用线程,并决定使用最现代的API(java.util.concurrent包)。使用java.util.concurrent结束的线程API
这里就是我想要做的(伪):
//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);
我想运行在某一日期任务和重复,直到一定的时间。时间过后,任务结束。我唯一的问题是如何以线程结束?
不,使用ScheduledExecutorService时,如果按照问题计划scheduleWithFixedDelay,则会多次调用run方法。 –