繁体   English   中英

使用java.util.concurrent API结束的线程

[英]Thread ending using java.util.concurrent API

我正在使用线程,因此决定使用最现代的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()函数),该线程可以自由用于其他任务。 使用计划程序调度任务以每天重复一次。

如果您不想执行连续任务,则可以选择几种方法。 我想说的一个简单的决定是,如果要安排新的一次性任务,则决定何时完成部分任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM