我读过 IntentService 为要完成的工作创建工作线程。如果我理解正确,那么这意味着工作将在 UI 线程以外的线程上完成。我的问题是
如果我的 Activity 正在尝试更新共享首选项并且此 intentService 也在更新共享首选项,那么这意味着我将遇到并发问题。正确的?所以我更好地使用 Service 而不是 IntentService,因为它在主 UI 线程上运行
请确认我的理解是否正确
最佳答案
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 中,对象不在线程上“运行”。方法在线程上运行。因此,服务不会“在主 UI 线程上”运行。所有服务的生命周期方法(例如,onCreate()
、onStartCommand()
)都在主应用程序线程上调用。这包括 IntentService
。 IntentService
恰好有一个 onStartCommand()
的内置实现,它将 Intent
路由到后台线程。
除此之外,不要在主应用程序线程上执行磁盘 I/O,这包括写入 SharedPreferences
。
如果您可能从多个线程写入 SharedPreferences
上的相同键,请使用并发编程技术。 Java 线程的出现时间与 Java 一样长,并且有 a lot written。关于如何在 Java 中进行适当的并发编程。
关于android - intentService 是否会导致 Activity 并发问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420492/