线程中卖票的代码实现

线程中卖票的代码实现。
class Demo  implements Runnable{
    private int ticket=10;
   //加入一个同步方法
     public synchronized void fun(){
         //把需要同步的地方放在同步方法之中
            if(this.ticket>0){
            try{
                Thread.sleep(100);
          }catch(Exception e){
         
          }
          System.out.println(Thread.currentThread().getName()+"卖票了:"+this.ticket--);
        }
     }
    public  void      run(){
           while(this.ticket>0){
                 this.fun();
       }
    }       
   }
  public class Test8{
       public static void main(String[] args){
                      Demo d=new Demo();
                      Thread t1=new Thread(d,"售票A");
                      Thread t2=new Thread(d,"售票B");
                      Thread t3=new Thread(d,"售票c");
                          t1.start();
                          t2.start();
                          t3.start();
  }                
  }
//上面的主要应该注意的就是,同步操作就是在方法之中加入一个syschronized关键字,表示此方法为同步方法。
//把需要同步操作的方法放在里面,就ok了

 

 

2、第二种写法

class Demo  implements Runnable{
    private int ticket=10;
   //加入一个同步方法

    public  void      run(){
           while(this.ticket>0){
              synchronized(this){
               if(this.ticket>0){
                try{
                Thread.sleep(100);
          }catch(Exception e){
         
          }
          System.out.println(Thread.currentThread().getName()+"卖票了:"+this.ticket--);
        }
        }
       }
    } 
}     

  public class Test10{
       public static void main(String[] args){
                      Demo d=new Demo();
                      Thread t1=new Thread(d,"售票A");
                      Thread t2=new Thread(d,"售票B");
                      Thread t3=new Thread(d,"售票c");
                          t1.start();
                          t2.start();
                          t3.start();
  }                
  }

 

//OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值