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()来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。
通过调用Thread类的start()来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu
时间片,就开始执行run(),这里run()称为线程体,它包含了要执行的这个线程的内容,run方法运行结束,此
线程随即终止。
**run()只是Thread类的一个普通方法,如果直接调用run(),程序中依然只有主线程这一个线程,其程序执行路径
还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到多线
程的目的**。
调用start()方可启动线程,而run()只是thread的一个普通方法,还是在主线程里执行。把需要并行处理的代码放在
run()中,start()启动线程将自动调用run().
手机扫一扫
移动阅读更方便
你可能感兴趣的文章