多線程(同步鎖)

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();
   }
}

發佈了54 篇原創文章 · 獲贊 68 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章