python thread快速调用

快速上手

线程的创建有两种,一种是函数绑定式,一种是类名调用式,下面分别介绍两种开发方式。

函数绑定式

调用threading.Thread(target=test)从而让绑定test函数,在执行start()后就会创建一个新的线程去执行绑定的test函数,具体操作如下。

  • threading.current_thread().name可以查看当前线程的名称
  • threading.activeCount()可以查看当前的线程数

示例

import threading
import time

def test():
    for i in range(5):
        print('[info] {p1} now is :{p2}'.format(p1=threading.current_thread().name,p2=i))
        # time.sleep(1)


def method():
    for i in range(5):
        print('[info] {p1} now is :{p2}'.format(p1=threading.current_thread().name,p2=i))
        time.sleep(1)


def thread_1():
    thread = threading.Thread(target=test)
    thread.start()

def thread_2():
    thread = threading.Thread(target=method)
    thread.start()



if __name__ == '__main__':
    thread_1()
    thread_2()
    print('[info] count='+str(threading.activeCount())+'!!!')

Thread的生命周期

  1. 创建对象时,代表 Thread 内部被初始化。
  2. 调用 start() 方法后,thread 会开始运行。
  3. thread 代码正常运行结束或者是遇到异常,线程会终止。

类名调用式

可以自定义一个类,然后继承Thread类,重写run()方法,run()方法里面就是这个线程要执行的内容,然后和函数绑定式一样,通过start()开启线程。

  • 示例
import threading
import time


class TestThread(threading.Thread):

    def __init__(self,name=None):
        threading.Thread.__init__(self,name=name)

    def run(self):
        for i in range(5):
            print(threading.current_thread().name + ' test ', i)
            time.sleep(1)


thread = TestThread(name='TestThread')
thread.start()


for i in range(5):
    print(threading.current_thread().name+' main ', i)
    print(thread.name+' is alive ', thread.isAlive())
    time.sleep(1)

其他属性

线程阻塞

join()提供线程阻塞手段,简单来说,就是可以规定线程什么时候该运行,延迟多久运行,哪个线程先运行、哪个后运行。

注意:在线程阻塞期间只有当前join指定的线程可以运行,其他的线程(如主线程)都将停止运行,等到join指定的线程满足释放条件之后才会更变为多线程状态,如实例所示。

  • join形参
def join(self, timeout=None):

如果不加参数则意味着需要等到线程结束之后才会开始执行

示例:

import threading
import time

def test():

    for i in range(5):
        print(threading.current_thread().name+' test ',i)
        time.sleep(0.5)


thread = threading.Thread(target=test,name='TestThread')
thread.start()
thread.join(1.0)#延迟一秒后运行

for i in range(5):
    print(threading.current_thread().name+' main ', i)
    print(thread.name+' is alive ', thread.isAlive())
    time.sleep(1)

daemon

在默认情况下,如果另外开了一个线程,这个时候主线程先结束了但是次线程还没有结束的话,主线程就会等待次线程,等到它结束了之后在进行。

如果次线程中daemon 属性默认是 False,这使得 MainThread 需要等待它的结束,自身才结束。

  • 示例
import threading
import time

def test():

    for i in range(5):
        print(threading.current_thread().name+' test ',i)
        time.sleep(0.5)


thread = threading.Thread(target=test,name='TestThread',daemon=True)
thread.start()
thread.join(1.0)#延迟一秒后运行

for i in range(5):
    print(threading.current_thread().name+' main ', i)
    print(thread.name+' is alive ', thread.isAlive())
    time.sleep(1)

参考资料

Python多线程编程(一):threading 模块 Thread 类的用法详解

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zeeland

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值