简体   繁体   English

线程与处理程序进行轮询

[英]Thread vs Handler for polling

I need a polling thread to perform some network operations every 5 mins. 我需要一个轮询线程才能每5分钟执行一些网络操作。 I came up with the following two solution. 我想出了以下两种解决方案。 Which would be better and why? 哪个更好,为什么? I am looking to have minimum cpu and battery usage. 我希望将CPU和电池使用量降到最低。

pollThread = new Thread(){
      public void run(){
          while(toggle) {
              // Do stuff
              sleep(FIVE_MINUTES);
          }
      }
};
pollThread.start();

OR 要么

Runnable doStuffRunnable = new Runnable() {
     @Override
     public void run() {
         // Do stuff
         handler.postDelayed(this, FIVE_MINUTES);
     }
}

The answer depends on whether you are using the Handler to handle other tasks as well. 答案取决于您是否也使用处理程序来处理其他任务。 If not, there won't be much difference; 如果没有,那就不会有太大的区别。 there will still be a thread that wakes up every 5 minutes to do what you want. 仍然有一个线程每5分钟唤醒一次,以执行您想要的操作。 If the handler also handles other tasks, using the handler is likely to be more efficient than having a separate thread for each task, as it requires only one thread, and may have optimizations with respect to processor usage. 如果处理程序还处理其他任务,则使用处理程序可能比为每个任务使用单独的线程更有效,因为它只需要一个线程,并且可以在处理器使用方面进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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