开发者

Should I use Handler class or synchronized functions for thread-to-thread communication

I'm quite a beginner at Android so here is the thing:

I have multiple threads in my game: the main activity, the renderer and the game loop.

So the question is: Should I derive class开发者_开发知识库es from Handler class and send messages to threads or should I use synchronized functions for thread-to-thread communication?

What are the pros and cons of these two approaches?

(I'm also not an expert in Java, C++ is my homeland)


Handlers are good when you need to bring the action back to the activity you're running.

When it comes to communication from the UI to other threads in my apps, I prefer to use threadsafe collecitons to manage the communication from one to another. For example, when I am developing a game, I will commonly have the UI thread report touch events to my game thread by inserting them into a LinkedBlockingQueue, which the game thread empties at its leisure.


The Handler was designed to simplify threading. You should use it where ever possible BUT you can only use Handlers on threads managed by a GUI event scheduler. For most games, the main UI and the OpenGL threads are managed by event schedulers and Handlers work just fine on them.


The two proposed options differ fundamentally. With Handlers you are posting a message for the thread that owns the handler. That is, you would post a message to the UI thread for it to modify the UI in some way. With synchronized methods, the thread that's sending the message will be the one doing the executing. The concurrency abstractions in Android are pretty good so I would urge you to use them whenever possible rather than rolling your own.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜