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

发布于 2024-12-07 09:53:33 字数 870 浏览 0 评论 0原文

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

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

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 certain 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧伤慢歌 2024-12-14 09:53:33

好吧,当任务不再执行时,您可以抛出异常,但这是相当残酷的替代方案:

  • 将任务调度一次,使任务了解调度程序,以便它可以在需要时重新调度自己完成当前迭代 - 但如果在最后时间之后,则立即返回。
  • 使用像 Quartz Scheduler 这样的东西,它更适合此类事情。

当然,第一个版本可以封装成更令人愉快的形式 - 您可以创建一个“SchedulingRunnable”,它知道何时运行子任务(提供给它)以及运行多长时间。

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.

二智少女 2024-12-14 09:53:33

当线程的 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);
}

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);
}
二智少女猫性小仙女 2024-12-14 09:53:33

如果你想做一个连续的任务:在 run 函数中创建一个 while 循环,时不时地检查它是否运行了足够长的时间。当任务完成时(run() 函数退出),线程可以自由地用于其他任务。使用调度程序将任务安排为每天重复。

如果您不想要连续的任务,您有多种选择。我想说的最简单的方法是,如果您想安排一项新的一次性任务,则决定何时完成部分任务。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文