package gaoji;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket,"AA").start();
new Thread(ticket,"BB").start();
new Thread(ticket,"CC").start();
}
}
class Ticket implements Runnable{
int ticke=20;
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
//使用sleep使多个线程都进入
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
//哪个线程获得锁哪个去进行判断,结束之后在释放
lock.lock();
if (ticke > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "买到了" + ticke--);
} else {
break;
}
}finally {
lock.unlock();
}
}
}
}