ReentrantLock 可重入锁
ReentrantLock是可重入锁,可以手动进行加锁和解锁操作。
tryLock方法:尝试是否能获得锁,成功则返回true并锁定,否则返回false
trylock():尝试一次
boolean locked = lock.tryLock();
System.out.println("m2..."+locked);
if (locked) {
lock.unlock();
}
trylock(long time, TimeUnit unit):在给定的时间内一直进行尝试
boolean locked = false;
try {
locked = lock.tryLock(5, TimeUnit.SECONDS);
System.out.println("m2..." + locked);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (locked) lock.unlock();
}
lockInterruptibly():如果一个线程调用lock方法,但是锁被占用,此线程进入等待状态,这个等待状态无法被打断。使用lockInterruptibly方法,可以使用interrupt来打断等待状态
public class ReentrantLock4 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
new Thread(()->{
//锁定
lock.lock();
try {
//让线程t1休眠很长时间,一直占用这把锁
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
Thread t2 = new Thread(() -> {
try {
/*
使用lockInterruptibly,可以在调用interrupt时打断线程的
等待状态
*/
boolean locked = false;
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("Interrupted!");
} finally {
if (((ReentrantLock) lock).isLocked()) lock.unlock();
}
});
t2.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打断t2的等待状态
t2.interrupt();
}
}
ReentrantLock可以指定为公平锁
公平锁:当锁释放时,总是由等待时间最长的线程获得锁
非公平锁:锁释放时,随机指定获得锁的线程
非公平锁的效率更高,因为它不用管每个线程的等待时间
代码
public class ReentrantLock5 extends Thread{
//在实例化ReentrantLock对象时传入true,代表使用公平锁
private Lock lock = new ReentrantLock(true);
@Override
public void run() {
/*
循环100次,每次打印当前获得锁的线程名,然后释放锁
锁为公平锁时,两线程交替获得锁
不为公平锁时,两线程的执行顺序是随机的
*/
for (int i = 0; i < 100; i++) {
lock.lock();
System.out.println(Thread.currentThread().getName()+"获得锁");
lock.unlock();
}
}
public static void main(String[] args) {
Thread t1 = new ReentrantLock5();
Thread t2 = new ReentrantLock5();
t1.start();
t2.start();
}
}
} |
|