多线程问题-火车售票模拟

java课本多线程内容
问题模拟5个站点卖票,票数100,不能多卖!
涉及难点线程同步问题
使用synchronized()代码块进行上锁解决

源代码



public class SaleTicket {
    public static void main(String[] agrs) {
        Ticket a=new Ticket("a");
        Ticket b=new Ticket("b");
        Ticket c=new Ticket("c");
        Ticket d=new Ticket("d");
        Ticket e=new Ticket("e");
         a.start();
         b.start();
         c.start();
         d.start();
         e.start();
        
    }
    

}
class Ticket extends Thread{
    static int  ticket=100;
    String name;
    static Object obj=new Object();
    public Ticket(String name) {
        super();
        this.name=name;
    }
    public void run() {
        while(true) {
            synchronized(obj) {
                if(ticket>0) {
                    
                System.out.println(name+"卖出第"+(101-ticket)+"张票");
                ticket--;
                }else
                    return;
                try{
                    Thread.sleep(10);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                
            }
            
            
        }
    }
    
}

你可能感兴趣的:(多线程问题-火车售票模拟)