A recipe to convert an asynchronous call into a synchronous one:
Let's assume the async call is called fooAsync()
, and that you have some way to check a result condition when the operation is completed. You can introduce your own volatile boolean fooComplete
to track this.
Then:
public void fooSyncWrapper() {
volatile boolean fooComplete = false;
Thread thread = new Thread() {
@Override
public void run() {
fooAsync();
while (!fooComplete) {
// busy wait on completion condition
fooComplete = checkIfComplete();
}
// task is completed, thread will join
}
};
thread.start();
thread.join();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…