zoukankan      html  css  js  c++  java
  • start() vs. run()

          I'm reading a Blog. But a rather familiar question occurred to me, "What's the difference between run() method and start() method in thread?". Let's test it with the following code:

    #FileName: threadingDemo.py
    #Python Version: 2.7
    #Authour: lxw
    #Date: 2015-1-28
    #Usage: Demos for threading.
    
    import time
    import random
    
    from threading import Thread
    
    class MyThread(Thread):
        '''
        Definition of my own Thread class.
        '''
    
        def __init__(self, name):
            Thread.__init__(self)    # essential
            self.name = name
            
        def run(self):
            amount = random.randint(3, 10)
            time.sleep(amount)
            outStr = "Thread {0} sleeps {1} seconds. Thread {0} has finished.".format(self.name, amount)
            print(outStr)
    
    def main():
        threads = []
        #Create 5 objects of MyThread.
        for index in range(5):
            th = MyThread(str(index))
            threads.append(th)
    
        print(threads)
        #Run the objects of MyThread.
        for index in range(5):
            threads[index].run()
    
    if __name__ == "__main__":
        main()
    else:
        print("Imported as a module")
    
    

          Note the code on Line 38. The output of the program is(Thread 0-Thread 4 never disorder.):

    [<MyThread(0, initial)>, <MyThread(1, initial)>, <MyThread(2, initial)>, <MyThread(3, initial)>, <MyThread(4, initial)>]
    Thread 0 sleeps 9 seconds. Thread 0 has finished.
    Thread 1 sleeps 6 seconds. Thread 1 has finished.
    Thread 2 sleeps 8 seconds. Thread 2 has finished.
    Thread 3 sleeps 7 seconds. Thread 3 has finished.
    Thread 4 sleeps 9 seconds. Thread 4 has finished.
    

    Let's make some modifications around Line 38.

        for index in range(5):
            threads[index].start()
    

          The new output of the program becomes(it differs every time you run the program according to the time each thread sleeped):

    [<MyThread(0, initial)>, <MyThread(1, initial)>, <MyThread(2, initial)>, <MyThread(3, initial)>, <MyThread(4, initial)>]
    Thread 4 sleeps 4 seconds. Thread 4 has finished.
    Thread 0 sleeps 8 seconds. Thread 0 has finished.
    Thread 3 sleeps 8 seconds. Thread 3 has finished.
    Thread 2 sleeps 9 seconds. Thread 2 has finished.
    Thread 1 sleeps 10 seconds. Thread 1 has finished.
    

          Now, do you understand what's the difference between run() method and start() method in thread?

    start():

          用start()来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。

    通过调用Thread类的start()来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu

    时间片,就开始执行run(),这里run()称为线程体,它包含了要执行的这个线程的内容,run方法运行结束,此

    线程随即终止。

    run():

          run()只是Thread类的一个普通方法,如果直接调用run(),程序中依然只有主线程这一个线程,其程序执行路径

    还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到多线

    程的目的

    总结:

          调用start()方可启动线程,而run()只是thread的一个普通方法,还是在主线程里执行。把需要并行处理的代码放在

    run()中,start()启动线程将自动调用run().

    Reference:

    python并发:对线程的介绍

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

  • 相关阅读:
    winform把所有dll打包成一个exe
    Windows10+Python3下安装NumPy+SciPy+Matplotlib
    Windows10+Python3+BeautifulSoup4 安装
    解决:无法在发送 HTTP 标头之后进行重定向。 跟踪信息: 在 System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>……
    "请求被中止: 未能创建 SSL/TLS 安全通道"解决办法
    被“1”和“l”给坑了
    谁把我的代码覆盖了
    jQueryUI datepicker 报错: TypeError: inst is undefined
    VS 附加不上w3wp.exe
    MySQL性能调优与架构设计——第 18 章 高可用设计之 MySQL 监控
  • 原文地址:https://www.cnblogs.com/lxw0109/p/start_run.html
Copyright © 2011-2022 走看看