public class Sample {
Lock lock = new ReentrantLock();
public void first() { // 当前线程连续持有 10 秒 sample 实例的锁
try {
lock.lock();
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void second() { // 当前线程在启动后的 5 秒内不断尝试获取 sample 实例的锁
boolean locked = false;
try {
locked = lock.tryLock(5, TimeUnit.SECONDS); // 参数 1:最长等待时间、参数 2:时间单位
System.out.println(locked);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (locked) {
lock.unlock();
}
}
}
}
public class Solution {
public static void main(String[] args) throws InterruptedException {
Sample sample = new Sample();
new Thread(sample::first).start();
TimeUnit.SECONDS.sleep(1);
new Thread(sample::second).start();
}
}
请教示例代码中,两个线程在竞争锁,但线程竞争的是 sample 对象的锁,还是 lock 对象的锁呢?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…