本帖最后由 杨卫腾 于 2012-6-6 16:43 编辑
- class Ticket implements Runnable
- {
- private int ticket = 100;
- //private String name;
- //Ticket(String name)
- //{
- //this.name = name;
- //}
- public void run()
- {
- while(ticket>0)
- {
- try
- {
- Thread.sleep(10);
- }
- catch(Exception e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"sale..."+ticket--);
- }
- }
- }
- class ThreadDemo4
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- Thread t3 = new Thread(t);
- Thread t4 = new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 毕老师说这个多线程程序有安全问题,我想了好久了,还是不太明白。比如线程0执行时的这个ticket=1>0 进入那个while循环打印,这时ticket=0,若线程2抢到这个执行权它不能进入while循环呀!怎么还能打印呢?我就想不明白,请大家帮帮我! |