【问题标题】:Using Handler or Thread with while true?使用 Handler 或 Thread with while true?
【发布时间】:2016-02-02 12:49:41
【问题描述】:

我想知道如果我希望在标志为真时每五秒发生一次任务,我应该使用什么。我在安卓设备上运行它,所以性能很重要。

选项一是处理程序:

public void handleLocation() {
    handler.postDelayed(new Runnable() {
        public void run() {
            Toast.makeText(mContext, "Five Seconds", Toast.LENGTH_SHORT).show();          // this method will contain your almost-finished HTTP calls
            if (currentLocation != null && isWorking) {
                setMockLocation(currentLocation);
                setMockLocation2(currentLocation);
            }
            handler.postDelayed(this, FIVE_SECONDS);
        }
    }, FIVE_SECONDS);
}

第二个选项是线程:

 public void run() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    if (isWorking) {
                        if (currentLocation != null)
                            setMockLocation(currentLocation);
                        setMockLocation2(currentLocation);
                    }
                    sleep(5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Toast.makeText(mContext, mContext.getString(R.string.err0_unknown), Toast.LENGTH_LONG).show();
            }
        }
    };

    thread.start();
}

你喜欢用什么?有没有更好的解决方案?

【问题讨论】:

  • 为什么不使用while(flag)?
  • handler.postDelayed 是首选选项,因为您还可以访问 UI 元素,这些元素执行 Thread 所需的任何额外代码。
  • @Peter 我还需要 UI 才能在后台运行。
  • @ρяσѕρєяK 我只需要在这个循环中设置MockLocation。 UI 在不同的线程中运行。它仍然是更可取的选择吗?
  • 我的意思是结合睡眠。 :)

标签: java android multithreading android-handler


【解决方案1】:

不应该有一个更喜欢的选项,而是知道差异并选择最适合特定场景的选项。

延迟发布

在这种情况下,代码将在处理程序附加到的同一线程上运行。

如果这是您的主 (UI) 线程,请确保您不要使用此方法执行长时间运行的任务。

这也意味着您不能保证任务每 5 秒准确运行一次。如果处理程序线程很忙,您的任务将不得不等待。

新线程

在第二种情况下,将启动一个新线程来处理此任务。在我看来,这仅适用于线程与应用程序具有相同生命周期并且经常忙碌的情况。否则,我会使用您未列出的第一个或第三个选项中的消息:

AsyncTask

它非常支持在任务运行后更新 UI。

异步任务默认在共享线程上运行,但您可以在线程池线程上执行:

new YourAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

IntentService

运行专用线程的另一种方法是启动服务。它有自己的生命周期,不会像异步任务那样受 UI 生命周期的影响。

TimerTask

这是可用的,但据我所知,与 postDelayed 技术相比没有优势。

【讨论】:

  • 就我而言,我需要在应用程序的生命周期内每 5 秒运行一次命令。 (它不一定是 5 所以如果它会被交付没关系) 我选择哪一个?我五秒钟做一次的任务简单而短暂。
  • 听起来像 postDelayed 为您的目的勾选了所有方框。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
相关资源
最近更新 更多