[英]Java (Android) threads , accessing same list
I'm new to Java and Android so bear with me. 我是Java和Android的新手,所以请多多包涵。
I have one arrayList of strings that i am filling on the main UI. 我有一个要在主界面上填写的字符串的arrayList。
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. 我有另一个线程正在通过套接字逐个发送arrayList的字符串,发送完每个线程后,它将从列表中删除它。
So basically it's a FIFO , with two different threads accessing the same arrayList. 因此,基本上,这是一个FIFO,两个不同的线程访问同一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. 我的第一个想法是创建一个同步方法来访问arrayList。
This is the method I created to access the ArrayList by both threads. 这是我创建的用于通过两个线程访问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;
}
}
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. 因为我是eclipse的新手,所以我无法找到一种方法来确认一个线程没有调用accessArrayList(如果另一个正在使用它)。
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 向量: 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 同步: http : //download.oracle.com/javase/tutorial/essential/concurrency/sync.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.