如何在特定时间后继续运行线程

4

我是一个有用的助手,可以为您进行翻译。以下是需要翻译的内容:

我有一个线程,想要每15分钟运行一次。目前,我正在从另一个类中调用此线程,如下所示:

Class B{
public void start(){
 while(true){
 new Thread(new A()).start();
   }
 }
}

Class A implements Runnable{
  @override
  public void run(){
   //some operation
  }
}

如何每15分钟调用线程A。


为什么不使用 sleep() 函数来暂停 15 分钟? - TheLostMind
我不确定如何使用那个。 - Ashish
你不能“调用”一个线程。你可以通过创建一个新的Thread对象t,然后调用t.start()来“创建”一个线程。但是你不能重复使用一个Thread对象:你只能调用一次start(),如果你想再次执行相同的操作,你必须再次创建一个新的Thread对象。 - Solomon Slow
6个回答

5
您可以使用 Timer 或者 ScheduledExecutorService 来按时间间隔重复执行一个任务。

ExecutorService 可以调度命令在给定延迟后运行,或周期性地执行。

示例代码:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

executorService.scheduleAtFixedRate(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
}, 0, 15, TimeUnit.MINUTES);

查找 更多示例...


谢谢,我想我喜欢它。 - Ashish

3

请看类TimerTimerTask

这是一个用于在后台线程中安排将来执行任务的工具。任务可以安排为一次性执行,也可以按照固定时间间隔进行反复执行。


2

像这样使用sleep:

public void run(){
  while(true){
  // some code
   try{
       Thread.sleep(15*60*1000) // sleep for 15 minutes
      }
    catch(InterruptedException e)
    {
    }
   }
  }

2

替代选项使用类 java.util.Timer

Timer time = new Timer();
ScheduledTask st = new ScheduledTask();
time.schedule(st, 0, 15000);

或者

public void scheduleAtFixedRate(TimerTask task,long delay,long period);
甚至可以使用java.util.concurrent.ScheduledExecutorService的方法。
schedule(Runnable command, long delay, TimeUnit unit)

0

我认为一个 计时器 可以解决你的问题。

import java.util.Timer;
import java.util.TimerTask;

  class A extends TimerTask {
     @Override
     public void run(){
        //some operation
     }
  }

  A task = new A();
  final long MINUTES = 1000 * 60;
  Timer timer = new Timer( true );
  timer.schedule(task, 15 * MINUTES, 15 * MINUTES);

0

启动后无法再次启动。

您可以在run函数中放置Thread.Sleep(15*60*1000)以使其休眠,并用while将其包围以再次循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,