简体   繁体   中英

Java (Android) threads , accessing same list

I'm new to Java and Android so bear with me.

I have one arrayList of strings that i am filling on the main UI.

I have another thread that is sending one by one the strings of the arrayList through a socket, and after sending each one it erases it from the list.

So basically it's a FIFO , with two different threads accessing the same arrayList.

How can I make this reading and writing on the same list, thread safe? Because I read that I have to, thus preventing future errors.

My first thought was creating a synchronized method to access the arrayList.

This is the method I created to access the ArrayList by both threads.

public synchronized String accessArrayList(boolean add, boolean get, String utt)
{
    if(add){            
        mStrings.add(utt);
        return null;
    }
    else if(get){
        return mStrings.get(0);

    }
    else{
        mStringsUttComm.remove(0);
        return null;
    }


}

The main thread just add's strings to this list.

The second thread does this :

Runnable runner = new Runnable() {
      public void run() {
          while(!mString.isEmpty()){
                              //socket sends string               
              sc.actionPerformed(accessArrayList(false, true, null));
                              //erase from list
              accessArrayList(false, false, null);
          }

      }
};

Is this correct? Because I am new to eclipse and I can't find a way to confirm that one thread doesn't call accessArrayList if the other one is using it.

Thank you for your time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM