java同步基于参数 [英] java synchronizing based on a parameter
问题描述
我正在寻找一种基于它接收的参数同步方法的方法,如下所示:
I'm looking for a way to synchronize a method based on the parameter it receives, something like this:
public synchronized void doSomething(name){
//some code
}
I希望方法 doSomething
基于 name
参数进行同步,如下所示:
I want the method doSomething
to be synchronized based on the name
parameter like this:
线程1:doSomething(a);
Thread 1: doSomething("a");
线程2:doSomething(b);
Thread 2: doSomething("b");
线程3:doSomething(c);
Thread 3: doSomething("c");
线程4:doSomething(a);
Thread 4: doSomething("a");
线程1,线程2和线程3将执行代码而不进行同步,但线程4将等待,直到线程1完成代码,因为它具有相同的a值。
Thread 1 , Thread 2 and Thread 3 will execute the code without being synchronized , but Thread 4 will wait until Thread 1 has finished the code because it has the same "a" value.
谢谢
更新
基于都铎解释我认为我面临另一个问题:
这里是新代码的示例:
Based on Tudor explanation I think I'm facing another problem: here is a sample of the new code:
private HashMap locks=new HashMap();
public void doSomething(String name){
locks.put(name,new Object());
synchronized(locks.get(name)) {
// ...
}
locks.remove(name);
}
我没有填充锁定地图的原因是因为名称可以有任何值。
The reason why I don't populate the locks map is because name can have any value.
根据上面的示例,在同一时间由多个线程添加/删除hashmap中的值时会出现问题,因为HashMap不是线程 - 安全。
Based on the sample above , the problem can appear when adding / deleting values from the hashmap by multiple threads in the same time, since HashMap is not thread-safe.
所以我的问题是如果我使 HashMap
a ConcurrentHashMap
哪个是线程安全的,同步块会阻止其他线程访问locks.get(name)??
So my question is if I make the HashMap
a ConcurrentHashMap
which is thread safe, will the synchronized block stop other threads from accessing locks.get(name) ??
推荐答案
使用地图将字符串与锁定对象相关联:
Use a map to associate strings with lock objects:
Map<String, Object> locks = new HashMap<String, Object>();
locks.put("a", new Object());
locks.put("b", new Object());
// etc.
然后:
public void doSomething(String name){
synchronized(locks.get(name)) {
// ...
}
}
这篇关于java同步基于参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!