我基本上是在这条消息的底部做代码发布。
foobar() 将事件发布到公共(public)状态机中。
我还将触摸屏事件发布到公共(public)状态机中。
是真的,通过使用处理程序我没有同步问题吗?
(即,我的状态机不会同时通过触摸和 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);
}
};
最佳答案
Handler
的相同实例对象将处理在 Looper
上传递给它的消息/可运行的队列选择(默认主线程)。
所以不,如果您向 Handler 发送消息列表,它们将一次运行 1 条,永远不会并行。
但是如果您担心同步问题,您应该 synchronize(object) {}
您的代码在您的方法中围绕一个公共(public)对象,这样他们将等待对该公共(public)对象的锁定,这意味着您可以从任何地方调用该方法,并且它永远不会使用 synchronize(object) {}
与任何其他代码并行运行.
关于Android 处理程序、计时器和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13442601/