2011-09-30 26 views
0

我正在使用线程,并决定使用最现代的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); 

我想运行在某一日期任务和重复,直到一定的时间。时间过后,任务结束。我唯一的问题是如何以线程结束?

回答

1

好了,你可以当它不应该再执行任务抛出一个异常,但这是相当残酷的替代品:

  • 计划任务一次,使得意识到调度的任务,所以它可以在完成当前迭代时重新安排自己 - 但是如果它在最后时间之后立即返回,则可以立即重新安排。
  • 使用类似Quartz Scheduler这是更为这种事情设计的东西。

课程的第一版本可以被封装到一个较为愉快的形式 - 你可以创建一个“SchedulingRunnable”时,它的意思是运行一个子任务(提供给它),多长时间哪知道。

0

线程在其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); 
} 
+0

不,使用ScheduledExecutorService时,如果按照问题计划scheduleWithFixedDelay,则会多次调用run方法。 –

0

如果你想要做一个连续任务:在运行功能使while循环,每一个现在,然后检查是否已经运行足够长的时间。当任务完成时(run()函数退出),Thread可以自由地用于其他任务。使用调度程序来调度每天重复的任务。

如果你不想连续的任务,你有几个选项。我想说的很容易就是决定什么时候完成部分任务,如果你想安排一个新的一次性任务。