多线程 售票 (同步)

2021-07-13 16:08

阅读:505

标签:对象   rate   sleep   ted   tar   public   rup   print   nbsp   

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--+"张票");
            }
            }
            
        }
    }
}

 

多线程 售票 (同步)

标签:对象   rate   sleep   ted   tar   public   rup   print   nbsp   

原文地址:https://www.cnblogs.com/a709898670/p/9542034.html


评论


亲,登录后才可以留言!