习题买火车票

【原理】

 

 

package com.msb.test01;

/**
 * @author : liu
 * 日期:08:35:19
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class BuyTicketThread extends Thread{
    public BuyTicketThread() {
    }
    public BuyTicketThread(String name){
        super(name);
    }
    //一共10张票
    static int ticketNum=10;//多个对象共享10张票
    //每个窗口都是一个线程对象:每个对象执行的代码存入run方法中
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (ticketNum>0){
            System.out.println(getName()+"我买到了从北京到哈尔滨的第" + ticketNum-- + "火车票");
            }
        }
    }
}
package com.msb.test01;

/**
 * @author : liu
 * 日期:08:39:14
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Test {
    //这是一个main方法:是程序的入口
    public static void main(String[] args) {
        BuyTicketThread t1=new BuyTicketThread("窗口1");
        t1.start();
        BuyTicketThread t2=new BuyTicketThread("窗口2");
        t2.start();
        BuyTicketThread t3=new BuyTicketThread("窗口3");
        t3.start();
    }
}

 

posted @ 2022-11-19 08:57  爱的加勒比  阅读(26)  评论(0)    收藏  举报