码迷,mamicode.com
首页 > 编程语言 > 详细

多线程 售票 (同步)

时间:2018-08-27 14:52:25      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:对象   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!