在多线程或分布式环境中,经常需要用到锁,trylock有两种用法,一种是不带参数:不设置等待时间,获取失败立即返回false。另一种是带等待时间的,线程会先挂起等待设置的时间结束如果还未获取到锁则返回false。
下面来看一个多线程争抢锁的实例:
public void execWithLock(Lock lock, Supplier<Boolean> supplier) {
//Lock lock = new ReentrantLock(); //obtainLock(lockKey);
try {
String currThread = Thread.currentThread().getName();
if (lock.tryLock(4L, TimeUnit.SECONDS)) {
try {
System.out.println(currThread + "获取到锁了,开始执行方法");
Boolean result = supplier.get();
System.out.println(currThread + "函数执行结果:" + result);
Thread.sleep(3000L);
System.out.println(currThread + "方法执行结束");
} finally {
System.out.println(currThread + "解锁");
lock.unlock();
}
} else {
System.out.println(currThread + "没获取到锁");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RedisLockServiceImpl test = new RedisLockServiceImpl();
Lock lock = new ReentrantLock();
(new Thread() {
@Override
public void run() {
test.execWithLock(lock, () -> {
System.out.println("111This is function details...");
System.out.println("111......");
System.out.println("111Function is over.");
return true;
});
}
}).start();
(new Thread() {
@Override
public void run() {
test.execWithLock(lock, () -> {
System.out.println("222This is function details...");
System.out.println("222......");
System.out.println("222Function is over.");
return true;
});
}
}).start();
}