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 <code>run()</code> 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 <code>run()</code> method of
     * the receiver will be called by the receiver Thread itself (and not the
     * Thread calling <code>start()</code>).
     *
     * @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方法是正解。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值