一个关于多线程同步的问题。
问题:假设有火车票1000张,创建10个线程模拟10个售票点,每个售票点100毫秒买一张票。打印出售票过程,注意使用synchronized确保同一张票只能卖出一次。输出格式如下:
第4售票点卖出第100张票
第2售票点卖出第101张票 ……
我的解答是:
package ti2;
public class TicketsSell implements Runnable {
static int tickets = 1;
int num;
public TicketsSell(int num) {
this.num = num;
}
public synchronized void run() {
for (; tickets <= 100; tickets++) {
System.out.println("第" + num + "售票点卖出第" + tickets + "张票");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package ti2;
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();
}
}
运行结果就是不对!!其中老是出现不同售票点卖出同一张票!请各位高手指点指点!