开发者

Thread ending using java.util.concurrent API

I am working with threads, and decided to use the most modern API (java.util.concurrent package).

Here's what I want to do (pseudocode):

//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);

I want to run a task on a ce开发者_运维知识库rtain date and repeat it until a certain amount of time. After the time has elapsed, the task ends. My only question is how to end with the thread?


Well, you can throw an exception from the task when it should no longer execute, but that's fairly brutal Alternatives:

  • Schedule the task once, making the task aware of the scheduler, so it can reschedule itself when it's finished its current iteration - but just return immediately if it's after its final time.
  • Use something like Quartz Scheduler which is more designed for this sort of thing.

Of course the first version can be encapsulated into a somewhat more pleasant form - you could create a "SchedulingRunnable" which knows when it's meant to run a subtask (provided to it) and how long for.


A thread terminated when its run method exists. Seems like you just need to do the following:

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);
}


If you want to do a continuous task: in the run function make a while loop that every now and then checks if it has run long enough. When the task has completed (the run() function exits), the Thread is free to be used for other tasks. Use the scheduler to shedule the task to repeated daily.

If you don't want a continuous task you have several options. The easily one I would say is to decide when a partial task is done if you want to schedule a new onetime task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜