intentService 会导致 activity 的并发问题吗

Will intentService result in concurrecny issue with the activity

我读到 IntentService 为要完成的工作创建工作线程。如果我理解正确的话,那就意味着工作将在 UI 线程以外的线程上完成。我的问题是

如果我的 activity 正在尝试更新共享首选项并且此 intentService 也在更新共享首选项,那么这意味着我将 运行 陷入并发问题。正确的?所以我更好的用户服务而不是 IntentService 因为它 运行s on Main UI thread

请确认我的理解是否正确

I have read that IntentService create worker thread for the work to be done. If I understand correctly, then that means that the work will be done on a thread other than the UI thread.

正确。

if my activity is trying to update shared preferences and this intentService is also updating shared preferences then that means I will run into concurrency issue. Correct?

AFAIK,SharedPreferences 是线程安全的。因此,这将在一定程度上取决于这两个组件正在更新的内容。如果他们在单独的键下更新值,AFAIK 你应该没问题。但是,如果他们可能正在修改相同键的值,那么您可能会遇到问题(脏读等等)。

So I better user Service as opposed to IntentService as it runs on Main UI thread

在 Java 中,对象不会 "run" 在线程上。线程上的方法 运行。因此,服务不会 运行 "on Main UI thread"。所有服务的生命周期方法(例如,onCreate()onStartCommand())都在主应用程序线程上调用。这包括 IntentServiceIntentService 恰好有一个 onStartCommand() 的内置实现,它将 Intent 路由到后台线程。

除此之外,不要在主应用程序线程上执行磁盘 I/O,这包括写入 SharedPreferences

如果您可能从多个线程写入 SharedPreferences 上的相同键,请使用并发编程技术。 Java 线程的存在时间与 Java 一样长,并且 a lot written 关于如何在 Java.

中进行正确的并发编程