android - 为什么这里需要synchronized?

标签 android multithreading

通读 Android page on Services他们展示了一个基本的 IntentService 实现的例子。我计划实现类似的东西,因为它需要绑定(bind)。但是,我很困惑为什么他们需要使用下面的同步块(synchronized block)。如果有人可以阐明这一点,我将不胜感激。

// Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() < endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

最佳答案

示例试图模拟真实的 IntentService,例如下载文件。考虑这个故事: 你要求它下载一个文件,正如它在代码中所注释的那样,它通过等待 5ms 来模拟。为了调用等待函数,您需要一个同步块(synchronized block)。为什么? 因为如果你不这样做,它会抛出 IllegalMonitorStateException

关于android - 为什么这里需要synchronized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081203/

相关文章:

android - 更新时清除应用程序数据

android - 旋转后ImageView会重置为原始状态吗?

android - 是否可以在 Android 上创建一个 Parcelable 的 HashMap?

ios - 从后台线程执行 UI 更新,可能的陷阱

vb.net - 在线程之间共享信息

java - 当列为空时,如何使用 BaseAdapter 动态删除一行表?

javascript - 我正在尝试配置一个简单的 DbHelper,但在执行相同操作时出现错误

java - 无限循环的线程会导致CPU占用率过高吗

java - Java (Android) 中的优先级 ThreadPoolExecutor

java - ForkJoinPool 重置线程中断状态