Running Thread by calling start() and run(), what is the difference?

后端 未结 7 1632
粉色の甜心
粉色の甜心 2020-12-07 04:00

It may be a basic question, i was confused with this,

in one file i have like this :

public class MyThread extends Thread {
    @Override
    public          


        
相关标签:
7条回答
  • 2020-12-07 04:40
    • run() method after calling start() : this is executed by your thread which is created by you, it is allocated processor to run independently.

    • run() method called by you : executed from your calling thread.

    0 讨论(0)
  • 2020-12-07 04:40

    start() starts the thread. run() just runs the code, in the current thread.

    0 讨论(0)
  • 2020-12-07 04:42

    the simple answer to your question is this:

    run(): runs the code in the run() method, blocking until it's complete

    start(): returns immediately (without blocking) and another thread runs the code in the run() method

    0 讨论(0)
  • 2020-12-07 04:43

    Calling start() will create a new execution thread, and then the run() will be executed in the newly created thread

    where as directly calling run() will execute the code in the current thread

    0 讨论(0)
  • 2020-12-07 04:46

    In one line directly calling run() is synchronous (your code will block until run() returns) and calling start() (your code will not wait for run to complete as it is called in other thread obj) is asynchronous.

    When you directly use start() method, then the thread will run once using the Runnable instance you provided to it and then the thread will be unusable.

    But to leverage the Thread Pooling and Scheduling capabilities that are inbuilt in Java, extending a Runnable or Callable is the way to go.

    0 讨论(0)
  • 2020-12-07 04:54

    start() runs the code in run() in a new thread. Calling run() directly does not execute run() in a new thread, but rather the thread run() was called from.

    If you call run() directly, you're not threading. Calling run() directly will block until whatever code in run() completes. start() creates a new thread, and since the code in run is running in that new thread, start() returns immediately. (Well, technically not immediately, but rather after it's done creating the new thread and kicking it off.)

    Also, you should be implementing runnable, not extending thread.

    0 讨论(0)
提交回复
热议问题