火车站总共有100张票, 四个窗口同时卖票, 当票卖光了之后,提示"没票了...",
public class Train{
static int num = 100;
public class Train {
static int num = 100;
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
while(true) {
synchronized (args) {
try {
//方便查看效果
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (num>0) {
//提示第几号窗口买票 System.out.println(Thread.currentThread().getName()+"买了一张票");
num--;
System.out.println("还剩余"+num+"张票");
}else {
System.out.println(Thread.currentThread().getName()+"没票了...");
break;
}
}
}
}
};
Thread w1 = new Thread(r, "一号窗口");
Thread w2 = new Thread(r, "二号窗口");
Thread w3 = new Thread(r, "三号窗口");
Thread w4 = new Thread(r, "四号窗口");
w1.start();
w2.start();
w3.start();
w4.start();
}
}