多线程之售票问题!
byhsh 2010-04-21 05:29:40 运行结果只有一个售票窗口出票,是怎么回事?
class SaleTicket implements Runnable {
int tickets = 100;
public void run() {
while (tickets > 0) {
sale();
}
}
public synchronized void sale() {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "卖第"
+ (100 - tickets + 1) + "张票"); //打印第几个线程正在执行
tickets--;
}
}
}
public class TestSaleTicket {
public static void main(String[] args) {
SaleTicket st = new SaleTicket();
Thread t1=new Thread(st, "一号窗口");
Thread t2=new Thread(st, "二号窗口");
Thread t3=new Thread(st, "三号窗口");
Thread t4=new Thread(st, "四号窗口");
Thread t5=new Thread(st, "五号窗口");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}