gpt4 book ai didi

java - 保证回调总是异步执行的最佳方式?

转载 作者:行者123 更新时间:2023-11-29 21:40:15 27 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,它必须发出服务器请求,然后在请求完成时执行操作。下面是一些伪代码来帮助解释这种情况:

makeRequest(new SomeTask{
onDone() {
// Do actionB with queue
}
});

// Do actionA with queue. Must be execute first!!

下面是makeRequest的伪代码实现:

makeRequest(SomeTask task) {
if(canDoOptimization) { // if true, don't need to make request

// It's a bad idea to execute this immediately.
// Wish I could wait until the current thread of execution was done...
task.onDone();
return;
}

asyncTask = new AsyncTask<SomeTask, Void, Void>() {
doInBackground(SomeTask... task) {
// Make server request...

task.onDone();
}
}
asyncTask.execute(task);
}

通常 actionA 如预期的那样发生在 actionB 之前,但在我们可以避免网络请求的情况下,SomeTask.execute 会立即被调用。这会导致 actionB actionA 之前发生,这很糟糕。有什么办法可以保证这种情况不会发生?

我在 javascript 中遇到过几次这种情况。在这些情况下,我会用 setTimeoutsetImmediate 包装 SomeTask.execute 调用以保持正确的异步语义。

为清楚起见,这里是 JavaScript 中相同错误的示例:https://gist.github.com/xavi-/5882483

知道我应该在 Java/Android 中做什么吗?

最佳答案

欢迎来到同步世界。 Mutex 或锁对象通常用于此目的。 Is there a Mutex in Java?

您的 B 任务应该等待互斥体,任务 A 完成后会发出信号。这将确保正确的执行顺序,即 A 任务将在 B 之前完成。

关于java - 保证回调总是异步执行的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17351590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com