多线程Demo - 三个乘客在一个售票窗口买票 👋

设计一个高铁购票的应用程序,设车站初始有10张票,用线程模拟3个用户购票,每次购票1张,售完为止。使用多线程的同步控制编程。

public class CheZhan {
    public static void main(String[] args){
        Customer customer = new Customer();

        Thread thread1 = new Thread(customer, "1号乘客:");
        Thread thread2 = new Thread(customer, "2号乘客:");
        Thread thread3 = new Thread(customer, "3号乘客:");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class Customer implements Runnable{
    private int tickets = 10;

    @Override
    public void run() {
        while (tickets > 0){
            synchronized (Customer.class){
                if (tickets > 0){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tickets--;
                } else {
                    System.out.println("当日票次已售完!!!");
                    System.exit(0);
                }
            }
            System.out.println(Thread.currentThread().getName() + "购票一张,剩余票数:" + tickets);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容