天天看點

JAVA進階6.6——買票問題

class xc implements Runnable{
  public static int chePiao=100;
  String a=new String("1");//字元串随意定義,定義在函數外邊。
  
  //synchronized的作用是,讓它所管轄的代碼部分,要麼全部執行完,要麼全部不執行。
  public void run(){//synchronzed修飾函數不需要字元串,相當于預設是this。
    while(true){
      synchronized (a){//既可以修飾代碼塊,又可以修飾函數。
        if(chePiao>0){
          System.out.println("第"+Thread.currentThread().getName()+"個車站正在賣第"+(101-chePiao)+"張車票");
          chePiao--;
        }
        else{
          break;
        }
        
      }
    }
  }
}
public class Test{
  public static void main(String[] args){
    xc xc=new xc();
    Thread a=new Thread(xc);
    a.start();
    
    Thread b=new Thread(xc);
    b.start();
  }
}<span style="white-space:pre">    </span>//用接口實作。      
class xc extends Thread{
  public static int chePiao=100;
  public static String a=new String("1");//變成公共靜态的。
  
  //synchronized的作用是,讓它所管轄的代碼部分,要麼全部執行完,要麼全部不執行。
  public void run(){//synchronzed修飾函數不需要字元串,相當于預設是this。
    while(true){
      synchronized (a){//兩個線程的a是線程自己的,并不是公共的,是以我們要把a變成公共的。
        if(chePiao>0){
          System.out.println("第"+Thread.currentThread().getName()+"個車站正在賣第"+(101-chePiao)+"張車票");
          chePiao--;
        }
        else{
          break;
        }
        
      }
    }
  }
}
public class Test{
  public static void main(String[] args){
    xc xc=new xc();
    xc.start();
    
    xc xc2=new xc();
    xc2.start();
  }
}<span style="white-space:pre">    </span>//用繼承實作。