关于线程同步:卖票问题!! 为什么票数溢出!
//问题://假设有火车票100张,创建10个线程模拟10个售票点,每个售票点500毫秒买一张票。打印出售票过程,注意使用synchronized确保同一张票只能卖出一次。
class TicketsSell implements Runnable {
static int tickets=1;//实例化票数
int num;
public TicketsSell(int num) {// 构造方法
this.num = num;
}
public synchronized void run() {
//synchronized(this){// 同步该方法
for (int i=0; i< 100; i++) {
if(tickets<100) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第" + num + "售票点卖出第" + (tickets++) + "张票");
}
}
}
}
public class Station {
public static void main(String[] args) {
Thread wicket1 = new Thread(new TicketsSell(1));
Thread wicket2 = new Thread(new TicketsSell(2));
Thread wicket3 = new Thread(new TicketsSell(3));
Thread wicket4 = new Thread(new TicketsSell(4));
Thread wicket5 = new Thread(new TicketsSell(5));
Thread wicket6 = new Thread(new TicketsSell(6));
Thread wicket7 = new Thread(new TicketsSell(7));
Thread wicket8 = new Thread(new TicketsSell(8));
Thread wicket9 = new Thread(new TicketsSell(9));
Thread wicket10 = new Thread(new TicketsSell(10));
wicket1.start();
wicket2.start();
wicket3.start();
wicket4.start();
wicket5.start();
wicket6.start();
wicket7.start();
wicket8.start();
wicket9.start();
wicket10.start();
}
}
运行结果: 为什么会超出100张! 我找不出错误,知道的说下!