Это должно делать то, что вам нужно. Он использует notify()
и wait()
с известным объектом, чтобы сделать этот метод синхронным по своей природе. Все, что находится внутри run()
, будет выполняться в потоке пользовательского интерфейса и вернет управление на doSomething()
после завершения. Это, конечно, переведет вызывающий поток в спящий режим.
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);
}
}
}