多線程搶票

package gay;

class text extends Thread
{   
    static int s=100;
    public  synchronized void run()
    {
        while (true) {
            if(s>0) {
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                s--;
                System.out.println("還有"+s+"張票");
                
            }
        
        }
    }
}

public class Dss {
  public static void main(String[] args) {
      
      text a=new text();
      text b=new text();
      a.start();
      b.start();
}

}

這兩個的區別Thread是我new了好幾個對象,所以要不static 讓他們使用一個對象,Runnable是new了一個對象給多個thread所以不用static

package gay;

class text implements Runnable
{   
    int s=100;
    public synchronized void run()
    {
        while (true) {
            if(s>0) {
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                s--;
                System.out.println("還有"+s+"張票");
                
            }
        
        }
    }
}

public class Dss {
  public static void main(String[] args) {
      
      text a=new text();
     Thread aa=new Thread(a);
     Thread bb=new Thread(a);
      aa.start();
      bb.start();
}
}


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