[英]Is it possible to allow different thread both read to and write from the same collection?
I have the following wrapper: 我有以下包装:
public UserContianer{
private List<User> users;
public void add(User u){
users.add(u)
}
public void update(User u){
if(users.contains(u))
//updating with the new value u
}
public User get(int index){
return users.get(index);
}
}
I need to allow multiple thread to read from and write the container simultaneously such that 我需要允许多个线程同时读取和写入容器,以便
if read and written element of the list are the same then 如果列表的读写元素相同,则
if there's already a thread updating the element all read operation should be blocked untill the write operation's finished 如果已经有一个线程在更新元素,则所有读操作都应被阻止,直到写操作完成
if there's a thread reading some element, all write operations should be blocked until the reading's finished 如果有一个线程正在读取某些元素,则应阻止所有写入操作,直到读取完成
First of all, are such requirements even make sense? 首先,这样的要求是否有意义? I'm new to multithreading and maybe that's actualy not what I wanted.
我是多线程的新手,也许实际上不是我想要的。
Secondly, is it possible to implement the requirements in Java? 其次,可以用Java实现这些要求吗?
One option is to wrap your existing List in a synchronized version with Collections.synchronizedList(List<T> list)
. 一种选择是使用
Collections.synchronizedList(List<T> list)
将您现有的List包装在一个同步版本中。 This allows thread-safe use of the List, if all access is through the synchronized wrapper. 如果所有访问都是通过同步包装器进行的,则允许线程安全使用List。
Note that the elements in the List are references . 请注意,列表中的元素是引用 。 If you want to lock the List while you're making changes to objects, you'll need to synchronize at a higher level.
如果要在更改对象时锁定列表,则需要在更高级别进行同步。 One way to do this is to mark methods as
synchronized
. 一种方法是将方法标记为已
synchronized
。
public synchronized void update(User u) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.