package cn.ruhsang.gaoji;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 t1 = new TestLock2();
new Thread(t1).start();
new Thread(t1).start();
new Thread(t1).start();
}
}
class TestLock2 implements Runnable {
//定义一个Lock锁
private final ReentrantLock lock = new ReentrantLock();
int ticketNums = 10;
@Override
public void run() {
while (true) {
try {
lock.lock();//加锁
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}