用Runnable 方式和 继承 Thread方式实现火车站买票

Thread:

package com.yzx.demo3;

public class Test extends Thread{
    private static int num=100;//总票数
    private static Object obj=new Object();

    @Override
    public void run() {
        while (true){
            try {
                sleep(1000);//所有线程各卖出一张票停留1000毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj){//打开线程锁
                if(num>0){
                    System.out.println(Thread.currentThread().getName() + "出售的票号为:" + num + "的票");
                    num--;
                }else{
                    System.out.println("票已卖完");
                    System.exit(0);
                }
            }
        }
    }

    public static void main(String[] args) {
        Test  t=new Test();
        Thread  th=new Thread(t);
        th.start();

        Test  t1=new Test();
        Thread  th1=new Thread(t);
        th1.start();



    }
}

Runnable:

package com.yzx.demo3;

import sun.applet.Main;

public class Test2 implements Runnable{
    private static int num=100;//总票数
    private static Object obj=new Object();

    @Override
    public void run() {
        while (true) {//无限循环
            try {
                Thread.sleep(1000);//所有线程各卖出一张票停留1000毫秒
                synchronized (obj) {//打开线程锁
                    if (num > 0) {
                        System.out.println(Thread.currentThread().getName() + "出售的票号为:" + num + "的票");
                        num--;
                    } else {
                        System.out.println("票已卖完");
                        System.exit(0);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
        public static void main(String[] args) {
            Test t=new Test();

            Thread t1=new Thread(t,"一号窗口");
            t1.start();

            Thread t2=new Thread(t,"二号窗口");
            t2.start();

            Thread t3=new Thread(t,"三号窗口");
            t3.start();

    }
}

Runnable和Thread的区别:

Runnable的实现方式是实现其接口即可
Thread的实现方式是继承其类
Runnable接口支持多继承,但基本上用不到
Thread实现了Runnable接口并进行了扩展,而Thread和Runnable的实质是实现的关系,不是同类东西,所以Runnable或Thread本身没有可比性。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值