Python 多线程编程threading

1. 创建多线程对象

有两种方法可以创建线程对象:

(1)直接实例化

thread1 = threading.Thread(target=get_detail_html, args=("", ))
thread2 = threading.Thread(target=get_detail_url, args=("", ))

thread1.start()
thread2.start()

(2)通过继承 threading.Thread 来实现多线程编程,需要重载 run() 方法

class GetDetailHtml(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")


class GetDetailUrl(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail url started")
        time.sleep(4)
        print("get detail url end")


thread1 = GetDetailHtml("get_detail_html")
thread2 = GetDetailUrl("get_detail_url")
thread1.start()
thread2.start()

2. 设置子线程阻塞

上面的代码没有设置线程阻塞,如果想在子线程 thread1 和 thread2 跑完后,再接着跑主线程的代码,可以用.join()方法。

thread1.start()
thread2.start()

# 在thread.start() 之后,设置thread.join()
# .join()方法使当前线程终止之后才能从thread.join()返回
thread1.join()
thread2.join()

3.设置守护线程 

将子线程设置为守护线程,可以在主线程退出时, 也强制把子线程关闭

thread1.setDaemon(True)
thread2.setDaemon(True)

将两个子线程设置为守护线程,当主线程退出时,会把守护线程的子线程kill掉。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值