如何在AsyncTask doInBackground()中使用同步对象?

时间:2018-04-19 05:02:28

标签: java android multithreading android-asynctask thread-safety

我在后台线程中使用synchronized对象时遇到了麻烦。我已经在示例中明确指出了问题:

  1. 我写了这样的简单类:

    public class UIThreadClass {
    
       MyObject object;
    
       UIThreadClass() {
          object = new MyObject();
    
          object.doActionOne();
          object.doActionTwo();
      }
    }
    
  2. 现在我的任务是通过将两个方法放到非UI线程来改进代码。     我正在使用AsyncTask

    对于doActionOne()

    private static class DoActionOneTask extends AsyncTask<Void, Void, Void> {
    
        private WeakReference<MyObject> wObject;
    
        DoActionOneTask(MyObject object) {
            wObject = new WeakReference<>(object);
        }
    
        @Override
        protected Void doInBackground(Void... voids) {
           if(wObject.get() != null) {
              MyObject myObject = wObject.get();
              myObject.doActionOne();
           }
    
           return null;
        }
    }
    

    对于doActionTwo()

    private static class DoActionTwoTask extends AsyncTask<Void, Void, Void> {
    
        private WeakReference<MyObject> wObject;
    
        DoActionOneTask(MyObject object) {
            wObject = new WeakReference<>(object);
        }
    
        @Override
        protected Void doInBackground(Void... voids) {
           if(wObject.get() != null) {
              MyObject myObject = wObject.get();
              myObject.doActionTwo();
           }
    
           return null;
        }
    }
    

    现在在UI线程中调用它们

    public class UIThreadClass {
    
       MyObject object;
    
       UIThreadClass() {
          object = new MyObject();
    
          new DoActionOneTask(object).execute();
          new DoActionTwoTask(object).execute();
      }
    }
    
  3. 问题是:

      

    使用AsyncTask时 - 如何同步对象以确保   doActionTwo()总是在doActionOne()方法之后调用?。

    我尝试在doInBackground()中使用 synchronized(myObject){myObject.doActionOne();} 但是系统警告我myObject只是局部变量而且很难保证正确性。

    任何人都可以帮助我这种情况吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

你不需要做任何事情。它们将按照Android文档顺序执行

package window1;

import java.util.ArrayList;

public class Mine {
private ArrayList<String> listName = new ArrayList<>();
private String sal[]={"val","sa","de","dal","val","sa","de"};

     public static void main(String[] args) {

        for(int i =0;i<sal.length;i++)
        {

             if(!listname.contains(sal[i])) // If the element does not exist...
                 listName.add(sal[i]); // Add him
        }

       for(int j=0;j<listName.size();j++) System.out.println(listName.get(j));
    }
}