通过java多线程模拟火车售票,开始的错误程序
//售票类
class Runner implements Runnable{
private int Ticketnum=10;
int id;
Runner(int id){
this.id=id;
}
synchronized void SellTic(){
if(Ticketnum<=0){return;}
else {
System.out.println(Thread.currentThread().getName()+" sale "+Ticketnum--);
}
}
public void run(){
while(Ticketnum>0){
try{Thread.sleep(100);}catch(InterruptedException e){};
SellTic();
}
}
}
//测试类
public class Ticket {
public static void main(String args[]){
Thread t1 =new Thread(new Runner(1));
Thread t2 =new Thread(new Runner(2));
Thread t3 =new Thread(new Runner(3));
Thread t4 =new Thread(new Runner(4));
Thread t5 =new Thread(new Runner(5));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
输出结果五个线程没有共享Ticketnum变量,出现重复售票,错误原因在售票类中Ticketnum变量不是静态变量,即使值修改以后无法保留。改为,
private static int Ticketnum=10;问题解决
涉及线程共享问题要注意变量的全局性;
阅读(663) | 评论(0) | 转发(0) |