Java根据参数进行同步(名为互斥/锁) [英] Java synchronizing based on a parameter (named mutex/lock)
问题描述
我正在寻找一种基于接收到的参数来同步方法的方法,如下所示:
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
}
我希望基于这样的name
参数同步方法doSomething
:
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.
谢谢
更新
基于Tudor的解释,我认为我面临着另一个问题: 这是新代码的示例:
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);
}
之所以不填充锁映射,是因为name可以具有任何值.
The reason why I don't populate the locks map is because name can have any value.
基于上面的示例,由于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
设置为线程安全的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屋!