CSDN JAVA版主老紫竹的一段模擬買火車票的多線程代碼(轉)

class tt {   
  public static void main(String[] args) {   
    Runnable st = new SellThread();   
    new Thread(st).start();   
    new Thread(st).start();   
    new Thread(st).start();   
    new Thread(st).start();   
  }   
}   
  
class SellThread implements Runnable {   
  int tickets = 100;   
  
  Object obj = new Object();   
  
  public void run() {   
    while (true)
     {   
      synchronized (obj)
      
      {   
        if (tickets > 0) {   
          System.out.println(Thread.currentThread().getName() + "sell tickets" + tickets);   
          tickets--;   
        } else {   
          break;   
        }   
      }
      try {   
        Thread.sleep(100);   
      } catch (Exception e) {   
        e.printStackTrace();   
      }   
    }   
  }   
}  
 

 比較適合初學者理解同步,程序中的線程數到底有幾個的問題,我一直對這個沒有一個透徹的理解,實際上Thread xx=new Thread() ; 

xx.start()  只是啓動了一個線程,不管run()方法中是不是有無限循環如while(true)。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章