java Android:使线程每秒运行的标准方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16872419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:13:17  来源:igfitidea点击:

Android: Standard way to make a thread run every second

javaandroidmultithreading

提问by madhu

I'm trying to run a Threadclass every second. I cant use Runnable. I tried in the following way, but its throwing StackOverflowException. Can anyone please let me know a standard method to make a thread class run every second.

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

public class A extends Thread {

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

回答by Adam Stelmaszczyk

Use Timer's schedule()or scheduleAtFixedRate()(difference between these two) with TimerTaskin the first argument, in which you are overriding the run()method.

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

Example:

例子:

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

Your example causes stack overflow, because it's infinite recursion, you are always calling run()from run().

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

回答by Christian Rapp

Maybe you want to consider an alternative like ScheduledExecutorService

也许你想考虑像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);

回答by Eng.Fouad

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