android - 为什么在这个 IntentService 示例中使用同步块(synchronized block)?

标签 android

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/

相关文章:

android - Endless Scroll RecyclerView 总是返回顶部

android - 是否可以在动画重复时更改 ValueAnimator 的开始/结束值?

android - 在我的应用程序中禁用多指触摸

android - 在android中将二维字符串数组转换为ArrayList

android - 如何修复这些 proguard 警告

java - 使用 javaCV 从 Frames 在 Android 上录制视频

android - 找到屏幕尺寸后更改 FrameLayout 的尺寸

android - 通过命令行列出已安装的 sdk 包

java - 如何以编程方式退出 Android 应用程序?

java - float 按钮 setOnClickListener 不会在 Android 中被调用