java中如何获取自定义的synchronizedList?
我有一个扩展 ArrayList 的自定义列表 MyList,如下所示:
class MyList extends ArrayList<SomeParticularItem>{
[some methods...]
}
由于我对列表有并发读取和写入,我想同步它:
MyList mylist = (MyList) Collections.synchronizedList(new MyList());
这似乎没问题,.jar 已构建。然后,在运行时,我得到:
java.util.Collections$SynchronizedRandomAccessList cannot be cast to MyList
是否有更好的方法(有没有任何方法)来获取继承自某些 java.util.List 的列表的同步列表?
I have one customized list MyList that extends ArrayList, like this:
class MyList extends ArrayList<SomeParticularItem>{
[some methods...]
}
Since I have concurrent reads and writes to the list, I want to synchronize it:
MyList mylist = (MyList) Collections.synchronizedList(new MyList());
This seems to be fine, the .jar is build. Then, at runtime, I get:
java.util.Collections$SynchronizedRandomAccessList cannot be cast to MyList
Is there a better way (is there any way at all) to obtain a synchronized list of a list that inherits from some java.util.List?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么为什么不让 MyList 同步,或者简单地使用 List 接口
列表 mylist = Collections.synchronizedList(new MyList());
编辑:
您当然可以让 MyList 扩展 Vector,因为所有 Vectors 方法都已经同步,您可以节省一些工作。
Well why not make MyList synchronized, alternativly simply use the List interface
List mylist = Collections.synchronizedList(new MyList());
Edit:
You could of course let MyList extend Vector, since all of the Vectors methods are already synchronized you save some work.
最简单的方法是扩展
Vector
而不是ArrayList
。如果您想将其保留为ArrayList
,您也可以自己同步MyList
的方法。The easiest way to do it would be to extend
Vector
instead ofArrayList
. You could also synchronize the methods ofMyList
yourself if you wanted to keep it as anArrayList
.