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

本文介绍了Java中Thread.start()和Thread.run()的区别。start()方法用于启动线程,使run()方法在新的线程中执行,而直接调用run()方法则会使其在当前线程(通常是主线程)中执行。通过示例代码展示了两者不同的运行结果,并简单分析了start()方法的源码,揭示了线程的创建过程。

Thread start() 方法 ,是一个线程开始的方法

Thread run() 方法 ,就是一个普通的方法,可以理解为main方法里面的一个普通的方法

 下面写一个demo 理解下

  Thread thread = new Thread("other"){
            @Override
            public void run() {
                super.run();
                String threadName = Thread.currentThread().getName();
                long id = Thread.currentThread().getId();
                Log.e("------hxm","threadName = " + threadName + ", id = " + id);
            }
        };
        thread.start();

Thread start() 打印的结果为:------hxm: threadName = other, id = 1286

  Thread thread = new Thread("other"){
            @Override
            public void run() {
                super.run();
                String threadName = Thread.currentThread().getName();
                long id = Thread.currentThread().getId();
                Log.e("------hxm","threadName = " + threadName + ", id = " + id);
            }
        };
        thread.run();

Thread run() 打印的结果为:------hxm: threadName = main, id = 2

 

上面的对比不难发现 Thread start() 的线程为自己创建的other 它的run方法在other线程,Thread run() 则是main 它的run方法在主线程(Thread.currentThread().getName() 是获取当前线程的名字)

如果想更多的了解可以看下源码,这里我看的是android 里面的源码,可能存在修改

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".
         */
        // Android-changed: Replace unused threadStatus field with started field.
        // The threadStatus field is unused on Android.
        if (started)
            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);

        // Android-changed: Use field instead of local variable.
        // It is necessary to remember the state of this across calls to this method so that it
        // can throw an IllegalThreadStateException if this method is called on an already
        // started thread.
        started = false;
        try {
            // Android-changed: Use Android specific nativeCreate() method to create/start thread.
            // start0();
            nativeCreate(this, stackSize, daemon);
            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 */
            }
        }
    }
 
// Android-changed: Use Android specific nativeCreate() method to create/start thread.
// start0();
nativeCreate(this, stackSize, daemon);

看了下nativeCreate 方法里面也是run方法,不过nativeCreate作用了,说了就是创建或者开启一个线程的.

android 对这个地方有所修改,就是使用特有的nativeCreate() 方法,创建或者开启线程. 在往下看就是native 了,这个没有看,

 

run() 方法

直接调用的run 方法

在看target 是 什么

可以看出target 就是Runnable 对象本身.

 

 

### Python3 中 `threading` 模块 `run()` `start()` 方法区别 #### 基本概念 在 Python 的 `threading` 模块中,`Thread` 类提供了两个重要的方法:`start()` `run()`。它们的功能用途有所不同。 - **`start()` 方法** 调用 `start()` 方法时,Python 解释器会创建一个新的线程并执行该线程的目标函数。具体来说,当调用 `start()` 后,解释器会在新线程中自动调用 `run()` 方法[^1]。因此,开发者通常不需要直接调用 `run()` 方法,而是通过调用 `start()` 来间接触发它。 - **`run()` 方法** 这是线程的核心逻辑所在,默认情况下,`run()` 是由 `start()` 自动调用的。如果自定义了一个继承自 `Thread` 的子类,则可以重写 `run()` 方法来实现特定的任务逻辑[^2]。如果没有显式地提供目标函数(即未设置 `target` 参数),那么线程将默认执行这个 `run()` 方法中的代码。 #### 使用方式对比 以下是两种方法的具体使用场景: 1. **直接调用 `run()`** 如果直接调用了 `run()` 方法而不是通过 `start()`,则不会真正开启新的线程;相反,这相当于在一个单一线程环境中运行了 `run()` 所包含的内容。换句话说,这种方式失去了并发的优势[^3]。 2. **通过 `start()` 开启线程** 当需要真正的多线程支持时,应该始终使用 `start()` 方法。这样不仅可以利用操作系统的调度机制让多个任务同时进行,还可以享受更复杂的线程管理功能,比如同步原语等。 下面是一个简单的例子展示两者的差异: ```python import threading class MyThread(threading.Thread): def run(self): print(f"{self.name} is running") def main(): t = MyThread() # 错误示范 - 不会启动新线程 t.run() # 输出:"MyThread-1 is running" # 正确示范 - 将启动新线程 t.start() # 可能输出:"Thread-1 is running" if __name__ == "__main__": main() ``` 在这个例子中,第一次调用 `t.run()` 并没有实际启动任何新线程,而只是简单地打印了一条消息。第二次调用 `t.start()` 则确实开启了另一个独立的工作单元,并且它的行为取决于操作系统如何安排时间片给各个进程或线程。 #### 总结 为了充分利用 Python 提供的多线程能力,在大多数情况下都应该优先考虑使用 `start()` 方法而非手动调用 `run()` 。只有当你明确知道不希望引入额外开销或者根本无需涉及异步处理的时候才可能例外性地单独调用后者。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值