开发者

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               
            开发者_StackOverflow  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.


Take a look at vectors and synchronization :

Vectors : http://download.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html

Synchronization : http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜