gpt4 book ai didi

java - Android:在多线程Service中,LocalBroadcastManager安全吗?

转载 作者:行者123 更新时间:2023-12-01 11:48:20 24 4
gpt4 key购买 nike

在多线程服务中是LocalBroadcastManager.getInstance(this).sendBroadcast(),从不同线程调用,已经是线程安全的了吗?

public class MyService extends Service
{
// [...] define binder to allow access to doSomething() and doSomethingElse(), etc.

@Override
public IBinder onBind(Intent intent)
{
return binder;
}

public void doSomething()
{
new Thread(new Runnable()
{
public void run()
{
// [...] do something

// TODO is this threadsafe??
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.sendBroadcast(new Intent(DONE_SOMETHING));
}
}).start();
}

public void doSomethingElse()
{
new Thread(new Runnable()
{
public void run()
{
// [...] do something else

// TODO is this threadsafe??
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.sendBroadcast(new Intent(DONE_SOMETHING_ELSE));
}
}).start();
}
}

或者 LocalBroadcastManager.getInstance(this) 实际上始终为相同的上下文返回相同的实例,并且不会以其他方式同步,因此我实际上需要在 LocalBroadcastManager< 周围添加一定程度的同步,类似于:

MyService extends Service
{
private class SyncedLocalBroadcastManager
{
private LocalBroadcastManager broadcastManager;

SyncedLocalBroadcastManager(LocalBroadcastManager manager)
{
broadcastManager = manager;
}

public synchronized void send(Intent intent)
{
broadcastManager.sendBroadcast(intent);
}
}

private SyncedLocalBroadcastManager syncedBroadcastManager;

// [...] define binder to allow access to doSomething() and doSomethingElse(), etc.

@Override
public IBinder onBind(Intent intent)
{
syncedBroadcastManager = new SyncedLocalBroadcastManager(LocalBroadcastManager.getInstance(this));

return binder;
}

public void doSomething()
{
new Thread(new Runnable()
{
public void run()
{
// [...] do something

syncedBroadcastManager.send(new Intent(DONE_SOMETHING));
}
}).start();
}

public void doSomethingElse()
{
new Thread(new Runnable()
{
public void run()
{
// [...] do something else

syncedBroadcastManager.send(new Intent(DONE_SOMETHING_ELSE));
}
}).start();
}

}

或者还有其他首选/规范的方式吗?

我不想在已经很复杂的结构中添加不必要的同步,但我找不到任何确认。

最佳答案

是的,它是线程安全的,这里是来自实际类 getinstance 方法的代码 fragment :

public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}

因此您可以使用它而无需任何同步开销。

关于java - Android:在多线程Service中,LocalBroadcastManager安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28968166/

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