Java中Thread类的start()方法和run()方法

我们知道在Java中可以通过继承一个Thread类来实现一个线程类,继承以后,需要重载run()方法,但是在启动线程的时候则又是用start()方法,这个是几个意思,启动直接用run()不行么,我们试一下。

首先还是用start()方法启动线程:

public class RunAndStart extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RunAndStart thread1 = new RunAndStart();
        RunAndStart thread2 = new RunAndStart();

        thread1.start();
        thread2.start();
    }
}

输出结果:

Thread-1 0
Thread-0 0
Thread-1 1
Thread-0 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-1 4
Thread-0 4

跟我们想得差不多,再看下用run()方法启动线程:

public class RunAndStart extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RunAndStart thread1 = new RunAndStart();
        RunAndStart thread2 = new RunAndStart();

        thread1.run();
        thread2.run();
    }
}

输出结果:

main 0
main 1
main 2
main 3
main 4
main 0
main 1
main 2
main 3
main 4

看到这里,发现有点意思了啊,用start启动,我们看到的就是我们定义的线程,用run启动,那么我们看到的则是main线程,这是几个意思呢?

实际上是这样的,每个线程用start()启动都是在独立的调用栈中进行的,而第二种情况调用run()则是来自main线程的,我们在输出中已经看到了,run()方法用的是当前的调用栈,而不是由新建的一个调用站。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值