0

我有以下代码和 AsyncTask:

@Override
  protected ArrayList<Information> doInBackground(Integer... params)
{
 for (String[] info:informations)
      {
        final String[] infoFinal = info;
        Runnable runnable = new Runnable()

          @Override
          public void run()
          {
            Log.w("DEBUG", String.format("Runnable %s started",info[0]));
            synchronized (this)
            {
              publishProgress(InfoAsyncTask.this.counter++);
            }
            for (String infoInst: infoFinal )
            {
              try
              {
some long execution
...
 };
        runnable.run();
}

}

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

07-31 10:35:28.046: WARN/DEBUG(8983): Runnable 0 started
07-31 10:37:00.343: WARN/DEBUG(8983): Runnable 1 started
07-31 10:37:37.843: WARN/DEBUG(8983): Runnable 2 started
07-31 10:37:54.359: WARN/DEBUG(8983): Runnable 3 started
07-31 10:38:16.882: WARN/DEBUG(8983): Runnable 4 started
07-31 10:38:42.171: WARN/DEBUG(8983): Runnable 5 started

检查时间戳。
它们应该几乎相同(考虑到一些队列等待)。我认为当一个线程启动时,它会立即返回并让循环继续。是什么让我的 runnable 互相等待?

4

1 回答 1

1

Runnable不是线程。它只是一个interface单一的方法 - run(这使得它的行为与其他方法没有区别)。你应该new Thread(yourRunnable).start()改用。

虽然,考虑使用ThreadPoolExecutor而不是一堆普通线程。

于 2013-07-31T08:51:57.143 回答