一共有1000张电影票,可以在两个窗口领取,假设每次领取的时间为3000毫秒,
要求:请用多线程模拟领票过程并打印剩余电影票的数量(假设有a和b两个窗口卖票,并分别统计每个窗口卖了多少张票)
public class Movice {
public static void main(String[] args) {
Ticket1 t =new Ticket1();
Thread s1 =new Thread(t,"a");
Thread s2 =new Thread(t,"b");
s1.start();
s2.start();
}
}
class Ticket1 implements Runnable{
private int num =1000;
private int a = 0 ;
private int b = 0 ;
@Override
public void run() {
while(true){
String name =Thread.currentThread().getName();
synchronized (this) {
if(num<=0){
System.out.println("a总共卖了:"+a+"张票 " +" b卖总共卖了:"+b+"张票");
break;
}
try {
//睡眠3000毫秒(测试设小点,这太慢了)
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//判断是否是a窗口,是就计数
if("a".equals(name)){
a++;
System.out.println(name+"卖第"+num--+"张票");
}else if("b".equals(name)){
b++;
System.out.println(name+"卖第"+num--+"张票");
}
}
}
}
}
|
|