【问题标题】:Android handler, timer, and multithreadingAndroid 处理程序、计时器和多线程
【发布时间】:2012-11-06 17:07:53
【问题描述】:

我基本上是在做此消息底部的代码发布。 foob​​ar() 将事件发布到公共状态机中。 我还将触摸屏事件发布到公共状态机中。 是真的,通过使用处理程序我没有同步问题吗? (即,我的状态机不会同时通过触摸事件和 foobar 事件发送消息)?

private Handler handler = new Handler();
handler.postDelayed(runnable, 100);


private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      /* do what you need to do */
      foobar();
      /* and here comes the "trick" */
      handler.postDelayed(this, 100);
   }
};

【问题讨论】:

    标签: android multithreading timer handler state-machine


    【解决方案1】:

    Handler 对象的同一实例将处理在选择的Looper 上传递给它的消息/可运行对象队列(默认为主线程)。

    所以不,如果您向处理程序发送消息列表,它们将一次运行 1 条,永远不会并行。

    但是如果您担心同步问题,您应该在您的方法中围绕一个公共对象synchronize(object) {}您的代码,这样他们将等待锁定该公共对象,这意味着您可以从任何地方调用该方法,它永远不会使用 synchronize(object) {} 与任何其他代码并行运行。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多