package edu.wtbu;标签:Thread,lock,ReentrantLock,start,new,public From: https://www.cnblogs.com/123456dh/p/17232612.html
import java.util.concurrent.locks.ReentrantLock;
public class Demo01 {
public static void main(String[] args) {
Lock lock = new Lock();
new Thread(lock).start();
new Thread(lock).start();
new Thread(lock).start();
}
}
class Lock implements Runnable{
int ticketNums=10;
//定义lock锁
private final ReentrantLock lock=new ReentrantLock();//ReentrantLock:可重入锁
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(ticketNums--);
}else{
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}