黑马程序员技术交流社区

标题: 为什么加了同步之后运行就不穿插了?? [打印本页]

作者: 18573626921    时间: 2016-5-19 11:23
标题: 为什么加了同步之后运行就不穿插了??
package com.test;
//三个类ticket,sealWindow,ticketSealCenter,
//代表票信息,售票窗口,售票中心,售票中心分配一定数量的票(多个窗口实现多线程售票)
public class Test5 {
        public static void main(String[] args) {
        TucketSealCenter tsc=new TucketSealCenter();
        tsc.sell();
}
}
class SeaWindow implements Runnable{

        @Override
        public void run() {
                synchronized(this){
                while(Ticket.ticket>0){
                        try {
                               
                                        //Thread.sleep(102);
System.out.println(Thread.currentThread().getName()+"卖出了第"+Ticket.ticket--+"张票");
                                }
                         catch (Exception e) {
                               
                                e.printStackTrace();
                               
                        }
                }
                }
        }
       
}
class Ticket{
        public static int ticket=100;
}
class TucketSealCenter{
        public void sell(){
                SeaWindow sw=new SeaWindow();
                new Thread(sw,"售票窗口1").start();
                new Thread(sw,"售票窗口2").start();
                new Thread(sw,"售票窗口3").start();
                new Thread(sw,"售票窗口4").start();
        }
       
       
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2