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