习题,买车票 Runnable接口实现线程

【代码】

package com.msb.test03;

import sun.security.krb5.internal.Ticket;

/**
 * @author : liu
 * 日期:10:38:04
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class BuyTicketThread implements Runnable{
    int  ticketNum=10;
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            if (ticketNum>0){
                System.out.println("我在"+Thread.currentThread().getName()+"买到了火车票:"+ticketNum--);
            }
        }
    }
}
package com.msb.test03;

/**
 * @author : liu
 * 日期:10:41:49
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Test {
    //这是一个main方法:是程序的入口
    public static void main(String[] args) {
        //定义一个线程对象
        BuyTicketThread btt=new BuyTicketThread();
        //窗口1买票
        Thread t=new Thread(btt,"窗口1");
        //窗口2买票
        Thread t1=new Thread(btt,"窗口2");
        //窗口3买票
        Thread t2=new Thread(btt,"窗口3");
        t.start();
        t1.start();
        t2.start();
    }
}

【2】实际开发中,方式1继承Thread类还是方式2实现Runable接口这种方式多呢

(1)方式·1的话有java单继承的局限性,因为继承了Thread类,就不能继承别的类了

(2)方式2共享资源的能力也会强一些,不需要非得加上static来修饰

【3】Thread和Run拔了接口之间的关系

 

posted @ 2022-11-19 10:58  爱的加勒比  阅读(21)  评论(0)    收藏  举报