教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python中实现多线程有几种方式?

python中实现多线程有几种方式?

发布时间:2021-01-14   编辑:jiaochengji.com
教程集为您提供python中实现多线程有几种方式?等资源,欢迎您收藏本站,我们将为您提供最新的python中实现多线程有几种方式?资源

我们都知道,代码编程不是固定的东西,而是非常灵活的内容,根据不同的内容,我们可以拓展出很多条内容,最终目的还是为了可以实现结果,给大家举例说明其中一个最常用的多线程吧~以及实现的几种方式。

1. 用函数创建多线程

Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多线程。

举个例子

import time
from threading import Thread
 
# 自定义线程函数。
def target(name="Python"):
    for i in range(2):
        print("hello", name)
        time.sleep(1)
 
# 创建线程01,不指定参数
thread_01 = Thread(target=target)
# 启动线程01
thread_01.start()
 
 
# 创建线程02,指定参数,注意逗号
thread_02 = Thread(target=target, args=("MING",))
# 启动线程02
thread_02.start()

可以看到输出

hello Python
hello MING
hello Python
hello MING

2. 用类创建多线程

相比较函数而言,使用类创建线程,会比较麻烦一点。

首先,我们要自定义一个类,对于这个类有两点要求,

必须继承 threading.Thread 这个父类;

必须复写 run 方法。

来看一下例子为了方便对比,run函数我复用上面的main。

import time
from threading import Thread
 
class MyThread(Thread):
    def __init__(self, type="Python"):
        # 注意:super().__init__() 必须写
        # 且最好写在第一行
        super().__init__()
        self.type=type
 
    def run(self):
        for i in range(2):
            print("hello", self.type)
            time.sleep(1)
 
if __name__ == '__main__':
    # 创建线程01,不指定参数
    thread_01 = MyT
hread()
    # 创建线程02,指定参数
    thread_02 = MyThread("MING")
 
    thread_01.start()
thread_02.start()

当然结果也是一样的。

hello Python
hello MING
hello Python
hello MING

3. 线程对象的方法

上面介绍了当前 Python 中创建线程两种主要方法。

# 如上所述,创建一个线程
t=Thread(target=func)
 
# 启动子线程
t.start()
 
# 阻塞子线程,待子线程结束后,再往下执行
t.join()
 
# 判断线程是否在执行状态,在执行返回True,否则返回False
t.is_alive()
t.isAlive()
 
# 设置线程是否随主线程退出而退出,默认为False
t.daemon = True
t.daemon = False
 
# 设置线程名
t.name = "My-Thread"

至此,Python线程基础知识,我们大概都介绍完了。感兴趣的小伙伴可以多浏览看下内容哦~如果还想知道更多的python知识,可以到python学习网进行查询。

您可能感兴趣的文章:
Python之全局解释器锁GIL
零基础Python学习路线图,Python初学者必须要了解,让你少走弯路
什么是线程(多线程),Python多线程的好处
在python中线程和协程的区别是什么
Python创建线程
初识Python-Python的历史与优缺点
python gil是什么
新手学python看哪本书
学习Python却没看过这几本书,你就OUT了
Python进程锁Lock是什么

[关闭]
~ ~