什么时候会调用run()
是不是只要在start()启动线程后就会自动运行Thread里面的run()或者Thread继承类里面重写的run()?
那如果target被传入调用的方法,那么run()还会执行吗?是被传入的方法先执行还是run()先执行?
12
收起
正在回答
3回答
同学,你好。
1、是会执行run方法的,target: 被执行的对象,由run()方法执行,默认应为None, 意味着没有对象被调用。在run方法判断target是否存在。
2、self.target()为调用loop函数。自定义线程中有run方法,相当于重写了父类中的run方法,执行strat()后会直接执行。
如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~
慕瓜0155640
2019-11-22 15:52:53
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import threading import time import datetime def loop(): """新的线程执行的代码""" n = 0 while n < 5 : now_thread = threading.current_thread() print ( '{0}【loop 】now thread name:{1}' . format (datetime.datetime.now(),now_thread.name)) print (n) time.sleep( 1 ) n + = 1 def use_thread(): """使用线程来实现""" # 获取当前正在执行的线程名称 now_thread = threading.current_thread() print ( '{0} now thread name:{1}' . format (datetime.datetime.now(), now_thread.name)) # 设置线程 t = threading.Thread(target = loop, name = 'loop_thread' ) # 启动线程 t.start() # 挂起线程 t.join() if __name__ = = '__main__' : use_thread() |
时间,
2019-11-22 15:26:27
同学,你好。
1、启动线程后将自动调用 run()方法
2、run()方法还是会执行的,target传入的方法要看调用的位置在哪,一般线程执行的操作都会放在run方法中。
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import threading import time class LoopThread(threading.Thread): """ 自定义线程 """ def __init__( self , target = None ): super (LoopThread, self ).__init__() self .target = target def run( self ): print ( 'b' ) self .target() def loop(): """ 新的线程执行的代码 """ print ( 'a' ) if __name__ = = '__main__' : # 当前正在执行的线程名称 now_thread = threading.current_thread() t = LoopThread(target = loop) t.start() t.join() |
如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~
1.Python零基础入门
- 参与学习 人
- 提交作业 2727 份
- 解答问题 8160 个
想要进入Python Web、爬虫、人工智能等高薪领域,你需要掌握本阶段的Python基础知识,课程安排带你高效学习轻松入门,学完你也能听得懂Python工程师的行业梗。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧