不同的意图服务是否在同一线程上排队?

Are separate intent services queued on the same thread?

我有两个意图服务 - IntentServiceAIntentServiceB

它们具有以下 class 定义:

public class FirstService extends IntentService {
  public FirstService() {
      super("first_service");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
      Log.d("chi6rag", "first starts");
      for (long i = 0l; i < 10000000l; i++) {
          if (i == 0l) Log.d("chi6rag", "first started");
      }
      Log.d("chi6rag", "first ends");
  }
}

public class SecondService extends IntentService {
  public SecondService() {
      super("second_service");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
      Log.d("chi6rag", "second starts");
      for (long i = 0l; i < 10000000l; i++) {
          if (i == 0l) Log.d("chi6rag", "second started");
      }
      Log.d("chi6rag", "second ends");
  }
}

如果我在 Activity 中执行以下代码:

startService(new Intent(this, IntentServiceA.class)); startService(new Intent(this, IntentServiceB.class));

我在日志中看到以下内容:

D/chi6rag (11734): first starts

D/chi6rag (11734): first started

D/chi6rag (11734): second starts

D/chi6rag (11734): second started

D/chi6rag (11734): first ends

D/chi6rag (11734): second ends

虽然如果有人看到 Intent Service Docs,它清楚地提到它将 one intent at a time 传递给 IntentService

onHandleIntent 方法

问题:每个意图服务是否都有单独的工作线程?因为预期的日志是:

D/chi6rag (11734): first starts

D/chi6rag (11734): first started

D/chi6rag (11734): first ends

D/chi6rag (11734): second starts

D/chi6rag (11734): second started

D/chi6rag (11734): second ends

IntentService 执行以下操作:

  1. Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  2. Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about
    multi-threading
  3. Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

因为您有多个 类 扩展表单 IntentService,每个都有自己特定的 onHandleIntent。这些在单独的工作队列中处理。

参见 Extending the Intentservice

查看文档:IntentService

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

据我所知,所有请求都将在单个线程上处理 per IntentService。这意味着如果您创建许多 IntentService,则无法保证哪个 IntentService 的线程首先执行。

如果您想 运行 多个线程或在单个线程中按顺序工作,请尝试将 ExecutorServiceExecutors.newSingleThreadExecutor()runnable 一起玩 ExecutorService Examples