什么时候会调用run()

什么时候会调用run()

是不是只要在start()启动线程后就会自动运行Thread里面的run()或者Thread继承类里面重写的run()?

那如果target被传入调用的方法,那么run()还会执行吗?是被传入的方法先执行还是run()先执行?

正在回答

登陆购买课程后可参与讨论,去登陆

3回答

同学,你好。

1、是会执行run方法的,target: 被执行的对象,由run()方法执行,默认应为None, 意味着没有对象被调用。在run方法判断target是否存在。

http://img1.sycdn.imooc.com//climg/5dd7979e093c9cd107570230.jpg

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():
    """新的线程执行的代码"""
    = 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)
        += 1
 
 
def use_thread():
    """使用线程来实现"""
    # 获取当前正在执行的线程名称
    now_thread = threading.current_thread()
    print('{0} now thread name:{1}'.format(datetime.datetime.now(), now_thread.name))
    # 设置线程
    = threading.Thread(target=loop, name='loop_thread')
    # 启动线程
    t.start()
    # 挂起线程
    t.join()
 
 
if __name__ == '__main__':
    use_thread()


  • 提问者 慕瓜0155640 #1
    这是老师课程中的代码
    2019-11-22 15:54:08
时间, 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()
    = LoopThread(target=loop)
    t.start()
    t.join()

如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~

  • 提问者 慕瓜0155640 #1
    1.老师的第一个例子里面没有将target = loop的loop函数写在run函数里面,在t.start()后自动执行了loop()函数。那老师的这种写法还会执行Thread里面的run()吗?run()和loop()执行的先后顺序是什么?等会上传老师的而例子图片。 2.老师,你的程序run()中self.target()是在调用loop()吗?
    2019-11-22 15:50:20
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
1.Python零基础入门
  • 参与学习           人
  • 提交作业       2727    份
  • 解答问题       8160    个

想要进入Python Web、爬虫、人工智能等高薪领域,你需要掌握本阶段的Python基础知识,课程安排带你高效学习轻松入门,学完你也能听得懂Python工程师的行业梗。

了解课程
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码