Question:
I have a pre-populated array list. And I have multiple threads which will remove elements from the array list. Each thread calls the remove method below and removes one item from the list. Does the following code give me consistent behavior ?
- ArrayList
list = Collections.synchronizedList( new ArrayList()); - void remove(String item)
- {
- do something; (doesn't work on the list)
- list.remove(item);
- }
Check below sample code which doesn't do synchronization protection:
- package demo;
- import java.util.ArrayList;
- import java.util.List;
- public class MultiThreads {
- static class RThd implements Runnable{
- List
list = null; - int rc = 0;
- public RThd(List
list) - {
- this.list = list;
- }
- @Override
- public void run() {
- while(!list.isEmpty())
- {
- System.out.printf("\t[%s] Remove %d\n", Thread.currentThread().getName(), list.remove(0));
- rc++;
- }
- }
- }
- public static void main(String[] args) throws Exception{
- List
list = new ArrayList (); - for(int i=0; i<100000; i++) list.add(i);
- List
thdList = new ArrayList (); - ThreadGroup tg1 = new ThreadGroup("Group A");
- for(int i=0; i<10; i++)
- {
- RThd r = new RThd(list);
- thdList.add(r);
- new Thread(tg1, r).start();
- }
- while(tg1.activeCount()>0)
- {
- Thread.sleep(500);
- }
- int rcc = 0;
- for(RThd r:thdList) rcc+=r.rc;
- System.out.printf("\t[Info] Done (%d)!\n", rcc);
- }
- }
You can resolve this issue by below code change which will make sure every thread to access the list with synchronization protection:
- List
list = new ArrayList(); - list = Collections.synchronizedList(list);
- List list = Collections.synchronizedList(new ArrayList());
- ...
- synchronized (list) {
- Iterator i = list.iterator(); // Must be in synchronized block
- while (i.hasNext())
- foo(i.next());
- }
Supplement
* ThreadGroup in Java
沒有留言:
張貼留言