1 限时锁 和 公平锁
2 代码实现
public class TimeLock implements Runnable{
public static ReentrantLock reentrantLock = new ReentrantLock();
public void run() {
try {
if (reentrantLock.tryLock(5, TimeUnit.SECONDS)) {
Thread.sleep(6 * 1000);
}else {
System.out.println(Thread.currentThread().getName()+" get Lock Failed");
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
// 查询当前线程是否保持此锁。
if (reentrantLock.isHeldByCurrentThread()) {
System.out.println(Thread.currentThread().getName()+" release lock");
reentrantLock.unlock();
}
}
}
/**
* 5秒后, 线程1不再加锁,线程2可以执行run。
* 线程1 执行6秒, 线程2 不能加锁。
*/
public static void main(String[] args) {
TimeLock timeLock = new TimeLock();
Thread thread1 = new Thread(timeLock, "thread1");
Thread thread2 = new Thread(timeLock, "thread2");
thread1.start();
thread2.start();
}
}
public class FairLock implements Runnable{
public static ReentrantLock reentrantLock = new ReentrantLock(true);//按照队列执行
@Override
public void run() {
while (true){
try {
reentrantLock.lock();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " getLock");
}catch (InterruptedException e) {
}
finally {
reentrantLock.unlock();
}
}
}
public static void main(String[] args){
FairLock fairLock = new FairLock();
Thread thread1 = new Thread(fairLock);
Thread thread2 = new Thread(fairLock);
thread1.start();
thread2.start();
}
}