日期:2014-05-20 浏览次数:21179 次
public void setReparation( Reparation reparation ) {
boolean flag = false;
for (Iterator it = this.reparations.iterator();it.hasNext();){ //reparations为Collection
Reparation repa = (Reparation)it.next();
if (repa.getId() == reparation.getId()){
it.remove();
flag = true;
break;
}
}
if(flag){
this.reparations.add(reparation);
}
}
------解决方案--------------------
如果是读比较频繁,写比较少的话,可以用CopyOnWriteArrayList
这个是ArrayList并发版本
遍历的时候对list的添加和删除不需要锁
------解决方案--------------------
import java.util.Iterator;
import java.util.LinkedList;
public class test
{
public static void main(String[] args)
{
LinkedList<String> test = new LinkedList<String>();
for (int i = 0; i < 10000000; i++)
test.add("aaa");
Add cadd = new Add(test);
Traverse ctra = new Traverse(test);
final Thread add = new Thread(cadd);
final Thread tra = new Thread(ctra);
add.start();
tra.start();
}
}
class Add implements Runnable
{
LinkedList<String> test;
public Add(LinkedList<String> test)
{
this.test = test;
}
public void run()
{
while (true)
{
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (test)
{
for (Iterator<String> it = test.iterator(); it.hasNext();)
{
String tmp = (String) it.next();
it.remove();
}
}
}
}
}
class Traverse implements Runnable
{
LinkedList<String> test;
public Traverse(LinkedList<String> test)
{
this.test = test;
}
public void run()
{
while (true)
{
try
{
Thread.sleep(30);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (test)
{
for (String str : test)
{
if (str.isEmpty())
continue;
}
}
}
}
}