package com.xinnet.smart.base.util.model;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Locks {
final static Map<Long, Lock> map = new HashMap<Long, Lock>();
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
System.out.println("线程2:"+new Date());
try {
//Thread.sleep(10000);
testLock();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
System.out.println("线程3:"+new Date());
testLock();
}
public Lock lock(Long uuid) {
Lock ret = get(uuid);
ret.lock();
return ret;
}
public void unlock(Long uuid) {
get(uuid).unlock();
}
public synchronized static Lock get(Long uuid) {
Lock ret = map.get(uuid);
if (ret == null) {
ret = new ReentrantLock();
map.put(uuid, ret);
}
return ret;
}
public static void testLock(){
int i=0;
System.out.println(":"+new Date());
Lock lock =get(2L);
try {
lock.lock();
Thread.sleep(60000);
System.out.println(":2:"+new Date());
} catch (Exception e) {
e.printStackTrace();
} finally {
i++;
get(2L).unlock();
System.out.println(":"+i);
}
}
}