Android 文档对 IntentService 的描述如下:
[IntentService] creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
但是在接下来的例子中,他们在 onHandleIntent 方法中使用了一个同步块(synchronized block),就好像它被期望同时执行一样。
protected void onHandleIntent(Intent intent) {
synchronized (this) {
Some operations...
}
}
为什么他们在这里使用同步?我错过了什么吗?
最佳答案
在我看到的示例中,他们在 onHandleIntent() 中使用 wait() 休眠 5 秒。当您调用 wait() 时,您必须持有对象的锁——这就是他们使用 synchronize() 的原因。
所以 synchronize() 并不是很重要,它只是他们为示例选择的示例工作的细节。
关于android - 为什么在这个 IntentService 示例中使用同步块(synchronized block)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8452917/