Reputation: 1089
I need to iterate an ArrayList of String in a different thread, I don't need to add or delete items, just to iterate.
How can I do it?
Upvotes: 0
Views: 979
Reputation: 13139
The only issue you may encounter with this, that the reading thread accesses the same data as the publisher thread. For that you need to pass the reference to the other thread in thread-safely manner (i.e. via a field declared with volatile
modifier, using AtomicReference
or pass the memory barrier in reader and writer threads by any other way, like passing a ReentrantLock
or synchronize
block). Note - that you do not need to iterate it inside a synchronization. Just pass the memory barrier before reading the list.
For example (ReentrantLock):
private final ReadWriteLock lock = new ReentrantReadWriteLock();
final Lock w = lock.writeLock();
w.lock();
try {
// modifications of the list
} finally {
w.unlock();
}
.................................
final Lock r = lock.readLock();
r.lock();
try {
// read-only operations on the list
// e.g. copy it to an array
} finally {
r.unlock();
}
// and iterate outside the lock
Upvotes: 1
Reputation: 47984
Weill in its most basic form you do something like this. But it seems like there's a lot more to your question than you asked us?
final List<Item> items = new ArrayList<Item>();
items.addAll(stuff);
new Thread(new Runnable() {
public void run() {
for (Item item: items) {
System.out.println(item);
}
}
}).start();
Upvotes: 5
Reputation: 8604
Thread splashThread = new Thread() {
@Override
public void run() {
List<String> mylist = new ArrayList<String>();
mylist.add("I");
mylist.add("Am");
mylist.add("definitely");
mylist.add("becoming");
mylist.add("a");
mylist.add("better");
mylist.add("programmer");
Iterator<?> i1 = mylist.iterator();
while (i1.hasNext()) {
System.out.println(i1.next());
}
}
};
splashThread.start();
}
Upvotes: 0