ReentrantLock类的tryLock和tryLock(时间)
马 克-to-win:tryLock的方法就是试一下,如果能得到锁,就返回真,如果当时得不到,马上就返回假,绝不等。tryLock(时间)的用法就是 在规定的时间内设法得到锁。如果在规定的时间内最终不能得到锁,就返回假。注意,这个方法是可以被打断的,打断后的处理方法和上面的例子 lockInterruptibly的处理一样。
例1.9.8_a:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
class A {
private ReentrantLock lock = new ReentrantLock();
int ticketNum = 10;
public void buyOne() {
System.out.println("just before lock.lockInterruptibly();");
boolean succeed = lock.tryLock();
if (succeed) {
System.out.println(Thread.currentThread().getName()
+ "ticketNum is" + ticketNum);
if (ticketNum > 0) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNum--;
System.out
.println("模仿select * from table for update,执行的很慢,买了一张"
+ Thread.currentThread().getName()
+ "ticketNum is" + ticketNum);
}
lock.unlock();
}else{
System.out.println("没获得锁,一张");
}
}
public void buyBatch(int num) throws InterruptedException {
System.out.println("just before lock.lockInterruptibly();");
boolean succeed = false;
boolean sleepSucceed = false;
succeed = lock.tryLock(2, TimeUnit.SECONDS);
if (succeed) {
System.out.println("Thread.currentThread().getName()+ticketNum is"
+ ticketNum);
try {
Thread.sleep(5000);
sleepSucceed=true;
} catch (InterruptedException e) {
System.out.println("已经获得了锁了,几张的睡觉被打断,表示预备工作没做好,什么也不买");
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_43650923/article/details/101161930