I have two threads in an Android application, one is the view thread, and the other a worker thread. What i want to do is to sleep the worker thread until the view thread terminates the handling of the onDraw method.

How i can do this? is there a wait for a signal or something?

+8  A: 

Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:


When the view thread finishes its onDraw work, it calls this:


Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:

void onDraw() {
  synchronized (stick) {
} // end onDraw()

Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written.

Paul Brinkley

I don't think you're headed down the right track. Instead of looking at manipulating threads, you may want to try something like EventBus for messaging between a controller and a view.

+2  A: 

If you want a higher-level concurreny API (with things like Barriers), you could try the backport of the java 5 concurrency API, which works on java 1.3 and above, and may work on Android. The likes of Object.wait/notify will work, but they can be a bit terse.

+1  A: 

While blocking on an object as described in Paul Brinkley's answer would be the most efficient sollution, you may also want to look into using an Android MessageQueue by implementing a Handler.

This allows your threads to pass messages on a slightly more high level so may be less error prone and more manageble in the long run. The Api Demos has examples of this, one that comes to mind is the RemoteService example. (which incidently is also handy to look at if your threads need to communicate between processes)