Android排队后台线程

时间:2017-10-03 08:21:13

标签: java android multithreading

我有一个循环,其中创建了一些对象,我需要一个线程来处理这些对象。现在我收到OOM错误,因为所有线程都是同时启动的。

for (final String filePath : myFilesList) {
      obj1= ...
      obj2= ...

      tryUploadFile(obj1, obj2);
}


private void tryUploadFile(final Object obj1, final Object obj2) {
    new Thread() {
        @Override
        public void run() {
           //handle obj1 & obj2 (upload to Google Drive file)
        }
    }.start();
}

我需要将它放在队列中,所以当第一个线程完成第二个开始时,依此类推。我尝试使用IntentService,因为它一次只运行一个实例,但除了原始附加功能外,我无法向IntentService发送参数。任何帮助都是相关的。

2 个答案:

答案 0 :(得分:0)

不要每次在循环中创建一个线程,而不是使用单个线程,如AsyncTask和其他线程,如果你想为每个上传操作一个单独的线程,那么先等待完成,

方法1使用单线程并顺序上传,

private void tryUploadFile(final List<Object> myFilesList) {
    new AsyncTask<Void, Void, Void>() {
          @Override
          protected Long doInBackground() {
for (final Object filePath : myFilesList) {
      obj1 = ...
      obj2 = ...

      // handle obj1 & obj2
}          return null;
      }
    }.execute();
}

方法2为每个请求创建一个线程,但是按顺序。

tryUploadFile(myFilesList.get(0), myFilesList.get(1)); // using index 0 & 1 for obj1 & obj2 change accordingly.

private void tryUploadFile(final Object obj1, final Object obj2) {
    new AsyncTask<Void, Void, Void>() {
          @Override
          protected Long doInBackground() {
      // handle obj1 & obj2
      obj1 = ...
      obj2 = ...

}          return null;
      }
    @Override
    protected void onPostExecute() {
    // Remove the uploaded value from the existing list.
    mMyFilesList.remove(yourPosition); // Obj1
    mMyFilesList.remove(yourPosition); // obj2

// recursive call to same method until the size of list is >0.
tryUploadFile (mMyFilesList.get(yourUpdatedPosition), mMyFilesList.get(yourUpdatedPosition));
      }
    }.execute();
}

答案 1 :(得分:0)

不要创建那么多线程。将您的线程逻辑包装在Runnable类中,并将任务提交到ThreadPoolExecutor

代码段:

class UploadTask implements Runnable{
    Object obj1;
    Object obj2;
    public UploadTask(Object obj1,  Object obj2){
        this.obj1 = obj1;
        this.obj2 = obj2;
    }
    public void run(){
         //handle obj1 & obj2 (upload to Google Drive file)
    }
}



 BlockingQueue workQueue= new LinkedBlockingQueue<Runnable>(100); // Work pool size
 ThreadPoolExecutor executor = new ThreadPoolExecutor(
        Runtime.getRuntime().availableProcessors(),       // Initial pool size
        Runtime.getRuntime().availableProcessors(),       // Max pool size
        1, // KEEP_ALIVE_TIME
        TimeUnit.SECONDS, //  KEEP_ALIVE_TIME_UNIT
        workQueue);

for (final String filePath : myFilesList) {
      obj1= ...
      obj2= ...

      UploadTask task = new UploadTask(obj1, obj2);
      executor.execute(task);
}

如果您需要将值传递回UI线程,请在UI线程处理程序上发布消息[new Handler(Looper.getMainLooper())]