Sleep a thread until an event is attended in another thread

Question!

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

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

By : Lucas S.


Answers

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.

http://backport-jsr166.sourceforge.net/

By : skaffman


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:

stick.wait();

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

stick.notify();

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) {
    stick.notify();
  }
} // end onDraw()

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



Does COROUTINE a portable C++ library for coroutine sequencing point you in the right direction? It seems like an elegant solution that has lasted the test of time.....it's 9 years old!

In the DOC folder is a pdf of the paper A Portable C++ Library for Coroutine Sequencing by Keld Helsgaun which describes the library and provides short examples using it.

[update] I'm actually making successful use of it myself. Curiosity got the better of me, so I looked into this solution, and found it was a good fit for a problem I've been working on for some time!

By : Dan


This video can help you solving your question :)
By: admin