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()方法的区别
start() vs. run()的更多相关文章
- can't run roscore 并且 sudo 指令返回 unable to resolve host
I'm using ubuntu14 LTS. Problems: 1. When run roscore, got a mistake and an advice to ping the local ...
- DotNet Run 命令介绍
前言 本篇主要介绍 asp.net core 中,使用 dotnet tools 运行 dotnet run 之后的系统执行过程. 如果你觉得对你有帮助的话,不妨点个[推荐]. 目录 dotnet r ...
- 布里斯班Twilight Bay Run半程马拉松
自从8月3日跑了半马以后,又一鼓作气报了11月份的西昌马拉松.与第一次马拉松的只求完赛目标不同,第二次当然想取得一个更好的成绩.所以8月份练的比较猛,基本上是练2.3天休息一天,周么还要拉个长于21公 ...
- SVN:Previous operation has not finished; run 'cleanup' if it was interrupted
异常处理汇总-开发工具 http://www.cnblogs.com/dunitian/p/4522988.html cleanup failed to process the following ...
- linux 环境下运行STS时 出现must be available in order to run STS
linux 环境下运行ECLIPSE时 出现 “ A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be avai ...
- 0040 Java学习笔记-多线程-线程run()方法中的异常
run()与异常 不管是Threade还是Runnable的run()方法都没有定义抛出异常,也就是说一条线程内部发生的checked异常,必须也只能在内部用try-catch处理掉,不能往外抛,因为 ...
- jBPM4.4 no jBPM DB schema: no JBPM4_EXECUTION table. Run the create.jbpm.schema target first in the install tool.
jBPM4.4 no jBPM DB schema: no JBPM4_EXECUTION table. Run the create.jbpm.schema target first in the ...
- .NET跨平台之旅:探秘 dotnet run 如何运行 .NET Core 应用程序
自从用 dotnet run 成功运行第一个 "Hello world" .NET Core 应用程序后,一直有个好奇心:dotnet run 究竟是如何运行一个 .NET Cor ...
- 【svn】在提交文件是报错:previous operation has not finished;run 'cleanup' if it was interrupted
1.svn在提交文件是报错:previous operation has not finished;run 'cleanup' if it was interrupted2.原因,工作队列被占用,只需 ...
- svn报错cleanup failed–previous operation has not finished; run cleanup if it was interrupted的解决办法
今天在svn提交的时候它卡顿了一下,我以为已经提交完了,就按了一下,结果就再也恢复不了,也继续不了了... 报错 cleanup failed–previous operation has not f ...
随机推荐
- 怎样优雅的研究 RGSS3 番外(一) ruby 实现的后缀自己主动机
*我真的不会 ruby 呀* #encoding:utf-8 #==================================================================== ...
- javascript 最佳实践 ( 24 章 )
代码约定 易于维护, 形成了一套 JavaScript 代码书写的约定: 跟别的语言差不多, 不过 javascript 中的大括号一定要放在 行尾, 例如: function abc() { // ...
- LeetCode 递归(Recursion) 培训专题 讲解文章翻译 (附链接)
递归 - 时间复杂度 在本文中, 我们主要介绍如何分析递归算法程序中的时间复杂度.. 在一个递归程序中, 它的时间复杂度 O(T) 一般来说就是他总共递归调用的次数 (定义为 R) 以及每次调用时所 ...
- Spring4 MVC+Hibernate4 Many-to-many连接表+MySQL+Maven实例
这篇文章显示 Hibernate 的多对多实例,在 Spring MVC CRUD Web应用程序中连接表.我们将同时讨论管理多对多关系在视图和后端. 我们将使用应用程序的Web界面创建,更新,删除和 ...
- ssh远程登录+查看系统版本+使用scp命令上传下载
ssh远程登录命令简单实例 ssh命令用于远程登录上Linux主机. 常用格式:ssh [-l login_name] [-p port] [user@]hostname 更详细的可以用ssh ...
- go反射----2值
声明:文章内容取自雨痕老师<Go语言学习笔记> 和Type获取类型信息不同,Value专注于对象实例数据读写. 在前面章节曾提到过,接口变量会复制对象,且是unaddressable的,所 ...
- awk特征相同行的合并
[root@linux-node1 ~]# cat test.txt hisk01 hisk02 hisk03 hisk04 hisk05 hisk06 hisk07 hisk08 [root@lin ...
- PHP输出语句大杂烩
一 echo echo() 实际上不是一个函数,是php语句,因此您无需对其使用括号.不过,如果您希望向 echo() 传递一个以上的参数,那么使用括号会发生解析错误.而且echo是返回void的,并 ...
- 【BZOJ2793】[Poi2012]Vouchers 调和级数
[BZOJ2793][Poi2012]Vouchers Description 考虑正整数集合,现在有n组人依次来取数,假设第i组来了x人,他们每个取的数一定是x的倍数,并且是还剩下的最小的x个.正整 ...
- 宇视4G设备采用GB/T28181协议成功接入EasyGBS国标流媒体平台的设置流程
经过了多天的调试对接,终于将宇视的布控球顺利接入到了EasyGBS的国标平台,特地写一下对接过程中遇到的问题,希望能帮助大家避开一些麻烦: 第一步:电脑连接无线网络IPCWIFI,密码12345678 ...