Dies sollte tun, was Sie brauchen. Es verwendet notify()
und wait()
mit einer bekannten Aufgabe, diese Methode in ihrer Art synchron zu machen. Alles innerhalb von run()
wird auf dem UI-Thread ausgeführt und gibt nach Abschluss die Kontrolle an doSomething()
zurück. Dies wird natürlich den aufrufenden Thread in den Ruhezustand versetzen.
public void doSomething(MyObject thing) {
String sync = "";
class DoInBackground implements Runnable {
MyObject thing;
String sync;
public DoInBackground(MyObject thing, String sync) {
this.thing = thing;
this.sync = sync;
}
@Override
public void run() {
synchronized (sync) {
methodToDoSomething(thing); //does in background
sync.notify(); // alerts previous thread to wake
}
}
}
DoInBackground down = new DoInBackground(thing, sync);
synchronized (sync) {
try {
Activity activity = getFromSomewhere();
activity.runOnUiThread(down);
sync.wait(); //Blocks until task is completed
} catch (InterruptedException e) {
Log.e("PlaylistControl", "Error in up vote", e);
}
}
}
Ich verstehe nicht, was Aufruf von notify() auf einem String tun würde? –