多线程售票

 

public class SellTicket {
    public static void main(String[] args) {
        Ticket t =new Ticket(50);
        Thread t1 = new Thread(t,"科学一道");
        Thread t2 = new Thread(t,"科学二道");
        Thread t3 = new Thread(t,"科学三道");
        Thread t4 = new Thread(t,"科学四道");
        t1.start();t2.start();t3.start();t4.start();

    }
}

 

public class Ticket implements Runnable{
    //设置默认票数,不设置就是100
    private int num = 100;


    public Ticket(int num){//定义公共Ticket类
        this.num=num;
    }
    public void run() {
        //售票内容
        while (true){
            synchronized (this) {
                if (num > 0) {
                    System.out.printf("[%s]售出一张票,剩余%d张票 %n", Thread.currentThread().getName(), --num);
                } else {
                    System.out.printf("%n [%s] 票已售完,停止售票", Thread.currentThread().getName());
                    break;
                }
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}

 

posted @ 2021-01-29 21:07  谷先生  阅读(48)  评论(0)    收藏  举报