Thread.start()和Thread.run()之间有什么区别?

时间:2010-04-20 10:10:13

标签: java multithreading concurrency

为什么我们调用start()方法,后者又调用run()方法?
我们不能直接打电话给run()吗?

请举例说明存在差异。

9 个答案:

答案 0 :(得分:41)

不,你不能。调用run将在同一个线程中执行run()方法,而不启动新线程。

答案 1 :(得分:18)

  

为什么我们调用start()方法,后者又调用run()方法?

不,这不精确。 start()反过来不会调用run方法。 相反,它启动执行run方法的线程。这是原生的。

  

我们不能直接拨打run()吗?

如果直接调用run(),则不启动该线程,只需在同一调用方法上执行该方法。

  

请举例说明存在差异。

网络上有数百万。因此我不重复。

答案 2 :(得分:4)

实际上thread.start()创建了一个新线程并拥有自己的执行场景。

但是thread.run()没有创建任何新线程,而是在当前运行的线程中执行run方法。

所以大家,如果你正在使用thread.run(),那么如果你只想让一个线程执行所有run方法,那么想想多线程的用途是什么。

答案 3 :(得分:1)

因为start()不会调用run()。它启动一个新线程,在该线程中调用run()。

答案 4 :(得分:0)

你无法直接运行run()方法。每当使用thread.start()启动线程时,都会调用run()方法并执行进一步的操作。

答案 5 :(得分:0)

主要区别在于当程序调用 start()方法时,会创建一个新的Thread,并在新的Thread中执行run()方法内的代码。如果调用 run()方法没有新的线程被创建,run()内的代码将在当前的线程上执行。

大多数时候调用run()是错误或编程错误,因为调用者有意调用start()来创建新线程,并且许多静态代码覆盖工具(如findbugs)都可以检测到此错误。如果你想执行耗时的任务而不是总是调用start()方法,否则如果直接调用run()方法,主线程将在执行耗时任务时卡住。 Java线程中start和run之间的另一个区别是你不能在线程对象上调用两次start()方法。一旦启动,第二次调用start()将在Java中抛出IllegalStateException,同时可以调用run()方法两次。

答案 6 :(得分:0)

如果直接调用run(),代码将在调用线程中执行。通过调用start(),可以创建一个除主线程之外的新线程并且并行执行。

答案 7 :(得分:0)

因为start();已同步且run();是简单/常规方法。与java相同,知道从main();方法开始执行。因为线程知道从run();

开始执行

以下是Thread类的源代码:

run();代码:

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

start();代码:

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();是线程的管理者,如何管理等等,run();是线程工作的终点。

答案 8 :(得分:-1)

这是start方法完成的工作

synchronized public void start()
{ 
    //it calls start0() method internally and start0() method does below
    //create a real child thread and register with thread scheduler
    //create runtime stack for child thread
    //call run() on underlying Runtime object
}