public class Demo4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Tickets t=new Tickets();
        Thread th0=new Thread(t);
        Thread th1=new Thread(t);
        Thread th2=new Thread(t);
        th0.start();
        th1.start();
        th2.start();
    }

}
public class Tickets extends Thread{
    private int ticket=100;
    //对象锁
    private Object obj=new Object();
    public void run(){
        while(true){
            synchronized (obj) {
                if(ticket>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"出售第"+ticket--+"张票");
            }
            }
            
        }
    }
}

 

posted on 2018-08-27 14:31  九九九九  阅读(115)  评论(0编辑  收藏  举报