在常规JVM上,可以使用常规Java同步原语来实现。例如:// create a java.util.concurrent.Semaphore with 0 initial permitsfinal Semaphore semaphore = new Semaphore(0);// attach a value listener to a Firebase referenceref.addValueEventListener(new ValueEventListener() { // onDataChange will execute when the current value loaded and whenever it changes @Override public void onDataChange(DataSnapshot dataSnapshot) { // TODO: do whatever you need to do with the dataSnapshot // tell the caller that we're done semaphore.release(); } @Override public void onCancelled(FirebaseError firebaseError) { }});// wait until the onDataChange callback has released the semaphoresemaphore.acquire();// send our response messageref.push().setValue("Oh really? Here is what I think of that");但这在Android上不起作用。这是一件好事,因为在影响用户界面的任何事物中使用这种类型的阻止方法都是一个坏主意。我留下这些代码的唯一原因是因为我需要进行单元测试。在实际的面向用户的代码中,您应该采用事件驱动的方法。因此,我会“当数据进入时,发送我的消息”,而不是“等待数据到达然后发送我的消息”:// attach a value listener to a Firebase referenceref.addValueEventListener(new ValueEventListener() { // onDataChange will execute when the current value loaded and whenever it changes @Override public void onDataChange(DataSnapshot dataSnapshot) { // TODO: do whatever you need to do with the dataSnapshot // send our response message ref.push().setValue("Oh really? Here is what I think of that!"); } @Override public void onCancelled(FirebaseError firebaseError) { }});最终结果是完全相同的,但是此代码不需要同步,并且在Android上不会阻塞。