Java易失性链接列表

Java易失性链接列表,java,list,sorting,thread-safety,Java,List,Sorting,Thread Safety,我正在尝试对LinkedList进行非常特殊的排序。我使用一个ListIterator来查找我想要添加一个项目的位置,并且效果很好。唯一的问题是,我有多个线程想要添加和排序项目。添加本身是同步的,但LinkedList使用非易失性属性。那不安全,是吗?以下是我正在尝试做的(简化): 公共类测试{ 私有LinkedList=新建LinkedList(); 同步无效添加(最终长编号){ //迭代我们的排序列表 最终ListIterator迭代器=list.ListIterator(list.size

我正在尝试对LinkedList进行非常特殊的排序。我使用一个ListIterator来查找我想要添加一个项目的位置,并且效果很好。唯一的问题是,我有多个线程想要添加和排序项目。添加本身是同步的,但LinkedList使用非易失性属性。那不安全,是吗?以下是我正在尝试做的(简化):

公共类测试{
私有LinkedList=新建LinkedList();
同步无效添加(最终长编号){
//迭代我们的排序列表
最终ListIterator迭代器=list.ListIterator(list.size());
while(迭代器.hasPrevious()){
long current=iterator.previous();
如果(当前<数字){
if(iteratot.nextIndex()>=list.size()){
list.add(number);//我不再需要迭代器了
}否则{
iterator.next();
迭代器.add(number);
}
}
//这很难
//我需要这里的当前号码!(比添加的号码低一点)
}
}
}
上面的源代码与我正在做的非常相似,并且比原始代码简单得多


是否还有另一种列表类型是线程安全的,或者是另一种我不知道的解决方案?

只要访问和修改
测试的唯一方法是通过
Test.add()
,您的代码就是线程安全的

如果有其他方法访问/修改
Test.list
,您需要告诉我们更多信息。

您可以查看该方法

返回由指定列表支持的同步(线程安全)列表。为了保证串行访问,通过返回的列表完成对备份列表的所有访问至关重要


我唯一的想法是,LinkedList的属性不是易变的。那么这就没问题了?如果您使用的是synchronized,它会在关系建立之前建立,因此它是线程安全的。synchronizedList所做的唯一一件事就是用我的方法同步我正在做的访问,因此它将是无意义的。
public class Test {
    private LinkedList<Long> list = new LinkedList<Long>();

    synchronized void add ( final long number ) {
        // iterate our sorting list
        final ListIterator<Long> iterator = list.listIterator( list.size() );
        while (iterator.hasPrevious()) {
            long current = iterator.previous();
            if (current < number) {
                if (iteratot.nextIndex() >= list.size()) {
                    list.add( number ); // I don't need the iterator anymore
                } else {
                    iterator.next();
                    iterator.add( number );
                }
            }
            // This here gets difficult 
            // I need the current number here! (which is the one that is a little lower than the added one)
        }
    }
}