多线程Thread和Runnable

多线程实现:

一、继承Thread类

注意:继承的Thread类中本身就有sleep()和start()方法,可以直接调用。

public class Test04 extends Thread{
    private String name;

    public Test04(String name){
        this.name = name;
    }
    public void run(){
        for (int i = 0; i <5; i++) {
            System.out.println(this.name +"运行:"+i);
            try {
                sleep(1000);   //睡眠一秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Test04 thread1 = new Test04("A");
        Test04 thread2 = new Test04("B");
        thread1.start();
        thread2.start();
    }
}

二、实现Runnbale接口

public class Thread2 implements Runnable {
    private String name;

    public Thread2(String name){
        this.name = name;
    }

    @Override
    public void run(){
        for (int i = 0; i <5; i++) {
            System.out.println(this.name +"运行:"+i);
            try {
                Thread.sleep(1000);   //睡眠一秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread2 thread1 = new Thread2("A");
        Thread2 thread2 = new Thread2("B");
        new Thread(thread1).start();
        new Thread(thread2).start();
//        new Thread2("A").run();
//        new Thread2("B").run();
    }
}

注意:实现的Runnable接口中只有一个run()方法,因此sleep()和start()方法都需借助Thread类。
在这里插入图片描述
通过Thread类的有参构造实现
在这里插入图片描述
有待研究:为什么要通过start()方法去执行多线程,而不是直接调用run()方法呢?

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值