某电影院目前正在上映贺岁大片,共有100张票,而它有3个售票窗口,请设计一个程序模拟该电影院售票。
定义Sell类实现Runnable接口,很好的解决了单继承共享资源问题
public class Sell implements Runnable {
// 定义100张票,三个售票窗口售卖
private int tickets = 100;
Object obj = new Object();
@Override //重写run方法
public void run() {
while (true) {
synchronized (obj) { // synchronized(对象) 线程同步机制,解决了重复抢占现象
if (tickets > 0) {
try {
Thread.sleep(100); // sleep();休眠100毫秒
} catch (InterruptedException e) { //抛出异常
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第: " + (tickets--) + " 张票");
}
}
}
}
}
public class SellDemo {
public static void main(String[] args) {
Sell s = new Sell();
//三个售票口
Thread t1 = new Thread(s, "窗口1");
Thread t2 = new Thread(s, "窗口2");
Thread t3 = new Thread(s, "窗口3");
//启动线程
t1.start();
t2.start();
t3.start();
}
}