Thread run()和start()方法的区别

最近在使用FindBugs检查代码,下面这段代码:

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getEntryConfig();
                    }
                }).run();

FindBugs报了Multithreaded correctness级别的错误,具体信息如下:

Priority:Multithreaded correctness
Invokes run on a thread (did you mean to start it instead?)
This method explicitly invokes run() on an object.? In general, classes implement the Runnable interface because they are going to have their run() method invoked in a new thread, in which case Thread.start() is the right method to call.

在网上搜了一下Thread的run和start方法的区别,还是没有听明白。于是直接看代码。我发现,看源码是一个万能的办法,不管是解决问题还是消除疑惑。

我们看一下Thread类中的run方法:

    /**
     * Calls the run() method of the Runnable object the receiver
     * holds. If no Runnable is set, does nothing.
     *
     * @see Thread#start
     */
    public void run() {
        if (target != null) {
            target.run();
        }
    }

这个target对象就是我们在new Thread时传入的Runnable() 对象。所以上面那段代码其实等效如下:
        getEntryConfig();

这肯定不是我们想要的结果。再看start方法的实现:

    /**
     * Starts the new Thread of execution. The run() method of
     * the receiver will be called by the receiver Thread itself (and not the
     * Thread calling start()).
     *
     * @throws IllegalThreadStateException if the Thread has been started before
     *
     * @see Thread#run
     */
    public synchronized void start() {
        if (hasBeenStarted) {
            throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
        }


        hasBeenStarted = true;


        VMThread.create(this, stackSize);
    }
VMThread是一个封装类,其中的create是一个native方法:

native static void create(Thread t, long stackSize);
这么看来,我们调用start之后就把任务交给系统了,我们接下来该干嘛就干嘛了。接下来的解释可以参看:

Thread的run()与start()的区别

总结一下:

1.Java层想要另起线程完成某任务时,调用Thread的run方法是错误的;使用start方法是正解。


你可能感兴趣的:(Android)