可以使用lock 来保证多线程同步
如果只是想让线程顺序执行某个方法,比如
原方法
Java code
public synchronized void method1(){
//do something here
}
使用lock
Java code
private final ReentrantLock lock = new ReentrantLock();
public void mehtod1(){
lock.lock();
try{
//do something here
}finally{
lock.unlock();
}
}
还有一种可能是为了缓存数据并发性更好,比如某个类中有一个数据集用于做缓存的,为了让读写性能更佳(原方法不举例,因为不试过)
Java code
class RWDictionary {
//缓存集合 m
private final Map<String, Data> m = new TreeMap<String, Data>();
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
//读取锁,多个线程可以同时获取该锁
private final Lock r = rwl.readLock();
//写入锁,当写入锁被获取后,之后的读取乐和写入锁都得等待当前写入锁释放
private final Lock w = rwl.writeLock();
public Data get(String key) {
r.lock();
try { return m.get(key); }
finally { r.unlock(); }
}
public String[] allKeys() {
r.lock();
try { return m.keySet().toArray(); }
finally { r.unlock(); }
}
public Data put(String key, Data value) {
w.lock();
try { return m.put(key, value); }
finally { w.unlock(); }
}
public void clear() {
w.lock();
try { m.clear(); }
finally { w.unlock(); }
}
}
|