ReetrantLock 可重入锁
package com.kuang.Demo09Lock;
import java.util.concurrent.locks.ReentrantLock;
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{
private int ticket=10;
private final ReentrantLock lock= new ReentrantLock();
@Override
public void run() {
while (true){
try{
lock.lock();
if (ticket>0){
System.out.println(Thread.currentThread().getName()+"拿到了"+ticket--);
}else {
return;
}
} finally {
//解锁
lock.unlock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}