import java.util.concurrent.locks.ReentrantLock;
public class SellTickets {
public static void main(String[] args) {
TicketsWindow tw1 = new TicketsWindow();
Thread t1 = new Thread(tw1, "一号窗口");
Thread t2 = new Thread(tw1, "二号窗口");
t1.start();
t2.start();
}
}
class TicketsWindow implements Runnable {
private int tickets = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
//System.out.println(Thread.currentThread().getName());
lock.lock();
try {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()
+ "还剩余票:" + tickets + "张");
--tickets;
System.out.println(Thread.currentThread().getName()
+ "卖出一张火车票,还剩" + tickets + "张");
} else {
System.out.println(Thread.currentThread().getName()
+ "余票不足,暂停出售!");
try {
Thread.sleep(1000 * 6);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
}
}