日期:2014-05-20 浏览次数:20742 次
public void doSomething(Person person){
synchronized(person){
system.out.println("start: "+person.getId());
Thread.sleep(5000);
system.out.println("end: "+person.getId());
}
}
public void doSomething(Person person){
String id=person.getId();
synchronized(id){
...
}
}
//String id=person.getId();
synchronized(person.getId()){
....
}
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionalLock {
private final static Map<Thread, Person> relations = new ConcurrentHashMap<Thread, Person>();
private final static ReentrantLock lock = new ReentrantLock(false);
private final static Condition condition = lock.newCondition();
private Person person;
public ConditionalLock(Person p) {
this.person = p;
}
public void await() {
lock.lock();
try {
while (isAlreayLocked()) {
condition.await();
}
relations.put(Thread.currentThread(), person);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void singal() {
lock.lock();
try {
condition.signal();
relations.remove(Thread.currentThread());
} finally {
lock.unlock();
}
}
private boolean isAlreayLocked() {
Set<Entry<Thread, Person>> sets = relations.entrySet();
for (Entry<Thread, Person> entry : sets) {
Person other = entry.getValue();
if (other == null) {
continue;
}
if (this.person.equals(other)) {
return true;