多線程Runnable——賣票

線程Runnable

class 票子 implements Runnable {
    private int bill = 0;
    
    @Override
    public void run() {
  
        while (bill < 100) {
            synchronized(Object.class){ //同步代碼塊 一次只能進入一個線程
                if (bill < 100) {
    
                    bill++;
                    Thread thread = Thread.currentThread();  //獲取當前線程
                    System.out.println(thread.getName() + ": 第張" + bill-- + "票");
    
                } else {
                    System.out.println("賣完了");
                }
            }
        }
    }
}

主程序:添加數據

public class 賣票 {
    public static void main(String[] args) {
        票子 piao=new 票子();
        new Thread(piao,"1號牀").start();
        new Thread(piao,"2號牀").start();
        new Thread(piao,"3號牀").start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章