多线程(同步锁)

public class Site implements Runnable{
   private int count=10;  //记录剩余票数    
   private int num = 0;   //记录买到第几张票
   boolean isRunning=true;
   public void  run(){
      while(isRunning){
         sale();
      }
   }
   public synchronized void sale(){
      if(count<=0){
         isRunning=false;
         return;
      }
      //第一步:修改数据
      num++;
      count--;
      try {
         Thread.sleep(500); //模拟网络延时
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      //第二步:显示信息
      System.out.println(Thread.currentThread().getName()+"抢到第"+num+"张票,剩余"+count+"张票!");
   }

}

public class Test {
   public static void main(String[] args) {
      Site site = new Site();
      Thread person1= new Thread(site,"桃跑跑");
      Thread person2= new Thread(site,"抢票代理");
      Thread person3= new Thread(site,"黄牛党");
      System.out.println("********开始抢票********");
      person1.start();
      person2.start();
      person3.start();
   }
}

你可能感兴趣的:(多线程(同步锁))