java多线程中run和start区别

java多线程中run和start区别

run只是Thread里面的一个普通方法,start是启动线程的方法。

start()方法让一个线程进入就绪队列等待分配 cpu, 分到 cpu 后才调用实现的run()方法。

start()方法不能重复调用, 如果重复调用会抛出异常。
而 run 方法是业务逻辑实现的地方, 本质上和任意一个类的任意一个成员方法并没有任何区别, 可以重复执行, 也可以被单独调用。


1.start()方法

start()方法来启动线程,无需等待run方法体代码执行完毕,可以直接继续执行下面的代码;

jvm通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。

然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体,它包含了要执行的这个线程的内容, run方法运行结束, 此线程终止。

然后其他线程再抢cpu的控制权接着执行,这是真正实现了多线程。


2.run()方法

run()方法当作普通方法的方式调用。程序还是要顺序执行,要等待run方法体执行完毕后,才可继续执行下面的代码; 程序中只有主线程——这一个线程,其程序执行路径还是只有一条。这并非多线程,还只是单线程。


3.程序范例

public class MyThread1 extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName="+ this.currentThread().getName()+"begin");
            Thread.sleep(2000);
            System.out.println("run threadName="+this.currentThread().getName()+"end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Run1 {
    public static void main(String[] args) {
        final MyThread1 myThread1 = new MyThread1();
        System.out.println("begin="+System.currentTimeMillis());
        myThread1.run();
        System.out.println("end="+System.currentTimeMillis());
    }
}

在这里插入图片描述

public class Run2 {
    public static void main(String[] args) {
        final MyThread1 myThread2 = new MyThread1();
        System.out.println("begin="+System.currentTimeMillis());
        myThread2.start();
        System.out.println("end="+System.currentTimeMillis());
    }
}

在这里插入图片描述

4.参考资料

java多线程中run和start区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值