为什么需要同步?

时间:2014-09-28 03:03:30

标签: android multithreading

通过Android page on Services阅读,他们展示了一个基本的IntentService实现示例。我计划实现类似的东西,因为它需要绑定。但是,我很困惑为什么他们需要使用下面的synchronized块。如果有人能说清楚我会非常感激。

// 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);
      }
  }

1 个答案:

答案 0 :(得分:1)

示例正在尝试模拟真实IntentService,例如下载文件。考虑这个故事: 你要求它下载一个文件,因为它在模拟的代码中被注释,只需要等待5ms。要调用等待函数,您需要一个同步块。为什么? 因为如果你不这样做会引发IllegalMonitorStateException