8

我试图Thread每秒运行一堂课。我不能用Runnable。我尝试了以下方式,但它抛出了StackOverflowException. 任何人都可以让我知道使线程类每秒运行的标准方法。

public class A extends Thread {

    public void run() {
       //do my stuff
      sleep(1*1000,0);
      run();
    }
}
4

3 回答 3

18

在第一个参数中使用Timer's schedule()or scheduleAtFixedRate()(这两者之间的差异) with TimerTask,您将在其中覆盖该run()方法。

例子:

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        // TODO do your thing
    }
}, 0, 1000);

您的示例导致堆栈溢出,因为它是无限递归,您总是run()run().

于 2013-06-01T12:01:07.997 回答
3

也许您想考虑像ScheduledExecutorService这样的替代方案

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

/*This schedules a runnable task every second*/
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
  public void run() {
    DoWhateverYouWant();
  }
}, 0, 1, TimeUnit.SECONDS);
于 2013-06-01T11:59:20.567 回答
1
final ExecutorService es = Executors.newCachedThreadPool();
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable()
{
    @Override
    public void run()
    {
        es.submit(new Runnable()
        {
            @Override
            public void run()
            {
                // do your work here
            }
        });
    }
}, 0, 1, TimeUnit.SECONDS);
于 2013-06-01T12:11:42.853 回答