![image]()
可重入锁用法
![image]()
对比
![image]()
TestLock
package com.guo.gaoji;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2,"可爱的李悦" ).start();
new Thread(testLock2,"帅气的陈果" ).start();
new Thread(testLock2,"操蛋的黄牛" ).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 100;
//定义可重入锁 ReentrantLock
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
//加锁
lock.lock();
if (ticketNums>0){
System.out.println(Thread.currentThread().getName()+"-->抢到了第"+ticketNums--+"张票");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}