Java (Android) 线程,访问同一列表
我是 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下向量和同步:
向量:http ://download.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html
同步:http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html
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