多线程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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章