简体   繁体   English

Android处理程序,计时器和多线程

[英]Android handler, timer, and multithreading

I am basically doing the code post at the bottom of this message. 我基本上是在此消息底部进行代码发布。 foobar() posts an event into a common state machine. foob​​ar()将事件发布到通用状态机中。 I also have touchscreen events posted into the common state machine. 我还将触摸屏事件发布到普通状态机中。 Is it true, that by using a handler I have no synchronization issues? 是真的,通过使用处理程序,我没有同步问题? (ie, my state machine won't be message up by a touch even and a foobar event) at the same time? (即,我的状态机将不会同时通过触摸均匀和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);
   }
};

The same instance of Handler object will process through the queue of messages/runnables passed to it on the Looper of choice (main thread by default). Handler对象的同一实例将在选择的Looper (默认情况下为主线程) Looper它的消息/可运行队列中进行Handler

So NO, if you send a list of messages to the Handler they will be run through 1 at a time never in parallel. 因此,不,如果您将消息列表发送给Handler,则它们将一次不会同时通过1运行。

BUT if you are concerned about synchronization issues you should synchronize(object) {} your code inside your methods around a common object, that way they will wait for lock on that common object meaning that you could call that method from anywhere and it would never run in parallel with any other code using synchronize(object) {} . 但是,如果您担心同步问题,则应该在一个公共对象周围的方法中synchronize(object) {}代码synchronize(object) {} ,这样它们将等待对该公共对象的锁定,这意味着您可以从任何地方调用该方法,并且永远不会使用synchronize(object) {}与任何其他代码并行运行。

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

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