android - Don't know how use wait() and notify() in Java -
this question has answer here:
- how use wait , notify in java? 12 answers
i want make inside thread return did string, , i'd wait string other thins. i've been reading wait()
, notify()
dint it. can me?
here create thread operations
new thread( new runnable() { @override public void run() { synchronized(mensaje) { try { mensaje.wait(); mensaje = getfilesfromurl(value); } catch (interruptedexception e) { e.printstacktrace(); } } } }).start();
and here wait string mensaje changes
if string not "" show button , text
synchronized(mensaje) { if (mensaje.equals("")) { try { mensaje.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } btnok.setvisibility(view.visible); lblestado.settext(mensaje); }
all stuff inside method
notify()
, notifyall()
, wait()
work this:
when call wait()
releases mutex taken synchronized block , puts current thread sleep in queue.
notify()
grabs 1 waiting thread front of queue. thread reacquires mutex , continues running.
notifyall()
wakes threads in queue.
to use here pseudocode (lacks exception handling etc bit more clear):
// in thread supposed wait synchronized { while(!somecondition) { wait(); } // @ point other thread has made condition true , notified you. } // in other thread synchronized { // changes somecondition true. notifyall(); }
edit: or thilo wrote @ java.util.concurrent first. there might ready-made solution use case. no need use low-level constructs then.
correction: there ready-made solution use-case: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/future.html
and corresponding executor.
Comments
Post a Comment