ReentrantLock 简单模板封装
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* A simple adapter mode of {@link java.util.concurrent.locks.Lock}
*
* @since 1.8
*/
public final class LockAdapter {
private static Lock _lock_ = null;
public LockAdapter() {
this(new ReentrantLock());
}
public LockAdapter (Lock lock) {
_lock_ = lock;
}
// --------------------------------------------------------------------------------------------
public void lock(Runnable runnable) {
if (runnable == null) { return; }
_lock_.lock();
try {
runnable.run();
} finally {
_lock_.unlock();
}
}
public <R> R lock(Supplier<R> supplier) {
if (supplier == null) { return null; }
_lock_.lock();
try {
return supplier.get();
} finally {
_lock_.unlock();
}
}
}
ReentrantReadWriteLock 简单模板封装
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/**
* A simple adapter mode of {@link java.util.concurrent.locks.ReadWriteLock}
*
* @since 1.8
*/
public final class ReadWriteLockAdapter {
private static Lock _rl_ = null;
private static Lock _wl_ = null;
public ReadWriteLockAdapter() {
this(new ReentrantReadWriteLock());
}
public ReadWriteLockAdapter(ReadWriteLock rwl) {
_rl_ = rwl.readLock();
_wl_ = rwl.writeLock();
}
// --------------------------------------------------------------------------------------------
public void readLock(Runnable runnable) {
if (runnable == null) { return; }
_rl_.lock();
try {
runnable.run();
} finally {
_rl_.unlock();
}
}
public <R> R readLock(Supplier<R> supplier) {
if (supplier == null) { return null; }
_rl_.lock();
try {
return supplier.get();
} finally {
_rl_.unlock();
}
}
// --------------------------------------------------------------------------------------------
public void writeLock(Runnable runnable) {
if (runnable == null) { return; }
_wl_.lock();
try {
runnable.run();
} finally {
_wl_.unlock();
}
}
public <R> R writeLock(Supplier<R> supplier) {
if (supplier == null) { return null; }
_wl_.lock();
try {
return supplier.get();
} finally {
_wl_.unlock();
}
}
}