1.创建Win类
写入买票方法
public void mp(){
for (int i = 0; i <count ; i++) {
System.out.println("窗口"+name+"买了一张票:"+Psl.getPsl());
}
}
使Win类继承Thread重写run方法
class Win extends Thread{
private int count;
private String name;
@Override
public void run() {
mp();
}
public Win(int count, String name) {
this.count = count;
this.name = name;
}
public void mp(){
for (int i = 0; i <count ; i++) {
System.out.println("窗口"+name+"买了一张票:"+Psl.getPsl());
}
}
}
2.创建票的数量类 并定义其数量为1000
class Psl{
private static int count=1000;
public static int getPsl(){
if (count == 0) {
throw new RuntimeException("没有票了");
}
return count--;
}
}
3.创建线程进行测试
public static void main(String[] args) {
Win w1 = new Win(10,"窗口1");
Win w2 = new Win(15,"窗口2");
Win w3 = new Win(15,"窗口3");
Win w4 = new Win(20,"窗口4");
w1.start();
w2.start();
w3.start();
w4.start();
}
4.结果