java学习之——多线程

多线程两种实现方式的区别,以及相应的验证程序

1…多线程的两种实现方式都需要一个线程的主类,而这个类可以实现Runnable接口或继承Thread类,不管使用何种方式都必须在子类中重写run()方法,此方法为线程的主方法。

2…Thread类是Runnable 接口的子类,而且使用Runnable接口可以避免单继承局限,并且可以更加方便地实现数据共享。

代码如下:
使用Thread类:

package mutithread;

public class testThread {
    public static void main(String[] args) {
        myThread m1 = new myThread();
        myThread m2 = new myThread();
        myThread m3 = new myThread();
        m1.start();
        m2.start();
        m3.start();
    }
}
class myThread extends Thread{
    private int ticket = 5;
    @Override
    public void run(){//主方法
        for (int i=0;i<50;i++){
            if (this.ticket>0){
                System.out.println("卖票,ticket="+this.ticket--);
            }
        }
    }
}

运行结果

package mutithread;

public class testRunnable {
    public static void main(String[] args) {
        myThread1 m = new myThread1();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        Thread t3 = new Thread(m);
        t1.start();
        t2.start();
        t3.start();
    }
}
class myThread1 implements Runnable{
    private int ticket = 5;
    @Override
    public void run() {
        for (int i=1;i<50;i++){
            if (ticket>0){
                System.out.println("卖出第"+this.ticket--+"票");
            }
        }
    }
}

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值