通俗易懂的用例
import java.util.concurrent.locks.ReentrantLock;
public class BuyTicket {
public static void main(String[] args) {
Buy buy = new Buy();
new Thread(buy,"老王").start();
new Thread(buy,"老李").start();
new Thread(buy,"老张").start();
}
}
class Buy implements Runnable{
int ticketNum = 1000;
boolean flag = true;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (flag){
buy();
}
}
void buy(){
try {
lock.lock();
Thread.sleep(0);
if (ticketNum<0) {
flag = false;
return;
}
else{
System.out.println(Thread.currentThread().getName()+"买到,票还剩"+ticketNum--);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
lock.unlock();
}
}
}