线程中start和run方法的区别

先说java中实现多线程常用的两种方式:
   1:继承Thread类,并重写run()方法
   2:实现Runnable接口,实现run方法
实际上Thread类也是实现了Runnable接口

[Java] 纯文本查看 复制代码

?

1

2

3

public class Thread implements Runnable {

  ........


而Runnable接口只定义了一个run方法

[AppleScript] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

@FunctionalInterface

public interface Runnable {

    /**

     * When an object implementing interface <code>Runnable</code> is used

     * to create a thread, starting the thread causes the object's

     * <code>run</code> method to be called in that separately executing

     * thread.

     * <p>

     * The general contract of the method <code>run</code> is that it may

     * take any action whatsoever.

     *

     * @see     java.lang.Thread#run()

     */

    public abstract void run();

}


我们需要实现的多线程业务逻辑,都需要在run方法内实现。

而start()是Thread中定义的方法,以下是start()方法的源码

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public synchronized void start() {

        /**

         * This method is not invoked for the main method thread or "system"

         * group threads created/set up by the VM. Any new functionality added

         * to this method in the future may have to also be added to the VM.

         *

         * A zero status value corresponds to state "NEW".

         */

        if (threadStatus != 0)

            throw new IllegalThreadStateException();

 

        /* Notify the group that this thread is about to be started

         * so that it can be added to the group's list of threads

         * and the group's unstarted count can be decremented. */

        group.add(this);

 

        boolean started = false;

        try {

            start0();

            started = true;

        } finally {

            try {

                if (!started) {

                    group.threadStartFailed(this);

                }

            } catch (Throwable ignore) {

                /* do nothing. If start0 threw a Throwable then

                  it will be passed up the call stack */

            }

        }

    }


start()通过调用本地native方法start0来启动一个线程,本地方法内最终会调用run方法,这样就可以实现在另一个线程中运行我们需要的代码。
而单独运行run()方法,就跟我们调用普通接口实现方法一样了,并不会启动新的线程.
总结:
1、start()方法运行时,本地启动新的线程,线程中会调用run方法,程序不需要等待run方法执行完毕再执行后面的程序;

2、run()方法是我们编写需要新的线程执行代码的方法,单独运行是不会有多线程效果的。

更多技术资讯可关注:itheimaGZ获取

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值