首页 > 编程语言 > 详细

多线程 售票 (同步)

时间:2018-08-27 14:44:01      阅读:208      评论:0      收藏:0      [点我收藏+]
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--+"张票");
            }
            }
            
        }
    }
}

 

多线程 售票 (同步)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!