gpt4 book ai didi

java - 我的代码中的DataSnapshot会因为多线程而被覆盖吗

转载 作者:行者123 更新时间:2023-12-02 03:09:09 25 4
gpt4 key购买 nike

这里有一些圣诞夜多线程...:)
因为 FireBase ChildEventListener onChildAdded() 会连续调用每个条目,所以我的代码中的 DataSnapshot 是否会被覆盖,就像我在没有启动时启动的线程一样完成并且对 onChildAdded() 的新调用即将到来,DataSnapshot 会在我的线程内更改吗?

ChildEventListener userHistoryAddressChildEventListener = new ChildEventListener() {

@Override
public void onChildAdded(final DataSnapshot snapshot, String prevKey) {
new Thread(new Runnable() {
@Override
public void run() {
// get toy history for current user
UserHistory.ToyHistory toyHistory = snapshot.getValue(UserHistory.ToyHistory.class);
ToyManager.getInstance().addToyHistory(
mFireBaseAuth.getCurrentUser().getUid(),
toyHistory.getToy(),
toyHistory.getTime(),
toyHistory.getColor(),
toyHistory.getHistoryId());
}
}).start();
}

最佳答案

每次调用 onChildAdded 都会将其自己的不可变 DataSnapshot 实例传递给它。

我强烈建议避免为每个 child 启动这样的新线程。这很容易压垮其运行的设备或计算机。如果您需要将阻塞工作从回调中转移到另一个线程中,请考虑使用 Executor它可以将工作排队等待在适合系统和 ToyManager 的有界线程池上执行,但我们看不到它是如何实现的。

关于java - 我的代码中的DataSnapshot会因为多线程而被覆盖吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41315117/

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