Java (Android) 线程,访问同一列表

发布于 2024-11-07 00:09:30 字数 1162 浏览 3 评论 0原文

我是 Java 和 Android 新手,请耐心等待。

我有一个要在主 UI 上填充的字符串数组列表。

我有另一个线程通过套接字逐一发送 arrayList 的字符串,并在发送每个字符串后将其从列表中删除。

所以基本上它是一个 FIFO ,有两个不同的线程访问同一个 arrayList。

我怎样才能使这个阅读和写作在同一个列表上,线程安全?因为我读到我必须这样做,从而防止将来出现错误。

我的第一个想法是创建一个同步方法来访问 arrayList。

这是我创建的用于通过两个线程访问 ArrayList 的方法。

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;
    }


}

主线程只是将字符串添加到这个列表中。

第二个线程执行此操作:

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);
          }

      }
};

这是正确的吗?因为我是 eclipse 新手,我找不到一种方法来确认一个线程在另一个线程正在使用 accessArrayList 时不会调用它。

感谢您抽出时间。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文