Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep a thread until an event is attended in another thread

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?

like image 990
Lucas S. Avatar asked Sep 23 '08 15:09

Lucas S.


People also ask

Can sleep () method causes another thread to sleep?

Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

Does thread sleep block other threads?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.

What does sleep () do in thread Java?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Why thread sleep is not recommended?

If given a wait of 5000 Milliseconds(5 seconds) and an element just take just 1-2 seconds to load, script will still wait for another 3 seconds which is bad as it is unnecessarily increasing the execution time. So thread. sleep() increases the execution time in cases where elements are loaded in no due time.


1 Answers

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.

like image 146
Paul Brinkley Avatar answered Oct 14 '22 17:10

Paul Brinkley