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

后端 未结 12 1122
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    Even if programmatically we are not creating any thread, For every application, O.S will create a default thread to execute its code with CPU.

    Calling run method directly will make that run method execute in that main thread given by O.S.

    But the intention of creating a thread class is to make sure that run method executes in a different thread. Unless thread manager of O.S creates a thread, your run method will not get executed in a separate thread. To request O.S to create the separate thread you have to call start() method which will send a request to O.S to create a thread. Once O.S creates a thread, then O.S will automatically call run method of your thread class in that newly created thread context. And hence your purpose of creating a separate thread and executing your run method in a separate thread will be served.

    If you call run method directly, then it is like O.S is not creating any thread for you, and default main thread will execute your run method. No point of creating a separate thread class for that!

    Hope I am clear. Let me know if you need more explanation to answer your question.

    Note: Though books say JVM creates threads, internally JVM will have to send a request to thread manager driver of O.S layer to create a new thread in its thread pool. That's why I use O.S term more here than JVM.

提交回复
热议问题