Why we call Thread.start() method which in turns calls run method?

后端 未结 12 1121
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 01:40

Why do we call the thread object\'s start() method which in turns calls run() method, why not we directly call run() method?

12条回答
  •  感情败类
    2020-11-29 02:33

    Runnable is just an interface. A class implementing Runnable is nothing special, it just has a run method.

    Thread#start is a natively implemented method that creates a separate thread and calls Thread's run method, executing the code in the new thread.

    Thread implements Runnable. The code for run looks like this:

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    

    If the Thread instance was created by passing a Runnable to the Thread's constructor, the Runnable's run method is called.

    Otherwise, classes extending Thread have to override the run method in order for start to work.

    Calling run on Thread does NOT create a new thread.

提交回复
热议问题