Reputation:
I have two worker threads:
They would be singletons so that every part of app could use them.
public class DbThread extends Thread { public Handler handler; @Override public void run() { Looper.prepare(); handler = new Handler(); Looper.loop(); } }
They communicate via Handlers. My concern is synchronisation. Another Thread could try access Handler while it's being created in order to send message. How do I properly synchronise Handler access?
My idea is that thread which wants to access another thread's Handler should wait before Handler it's created. But I don't know how to accomplish this.
Upvotes: 1
Views: 178
Reputation: 6862
I had some success implementing this solution.
You will hide the looper inside an HandlerThread, and you can wait until the thread is ready to receive messages.
It works because the getLooper call inside waitUntilReady
will block until the looper is initialized. Doing that you not only will be sure that the handler has been created, but also that your thread is ready to receive messages.
Upvotes: 2