简体   繁体   中英

Android: Standard way to make a thread run every second

I'm trying to run a Thread class 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.

public class A extends Thread {

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

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

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() .

Maybe you want to consider an alternative like 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);
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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