python多线程的实现方式

2025-12-01 0 45,560

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

方法一:创建threading.Thread对象

import threading
def tstart(arg):
	print(f"{arg}running" )
if __name__ == '__main__':
	t1 = threading.Thread(target=tstart, args=('This is thread 1',))
	t2 = threading.Thread(target=tstart, args=('This is thread 2',))
	t1.start()
	t2.start()
	print("This is main function")

方法二:继承于threading.Thread,重写方法run()

import threading
import time


# 重写一个类,继承于threading.Thread
class MyThread(threading.Thread):
    def __init__(self, jobName):
        super(MyThread, self).__init__()
        self.jobName = jobName

    # 重写run方法, 实现多线程, 因为start方法执行时, 调用的是run方法;
    # run方法里面编写的内容就是你要执行的任务;
    def run(self):
        print("这是一个需要执行的任务%s。。。。。" %(self.jobName))
        print("当前线程的个数:", threading.active_count() )
        time.sleep(1)
        print("当前线程的信息:", threading.current_thread())
if __name__ == '__main__':
    t1 = MyThread("name1")
    t2 = MyThread("name2")
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print("程序执行结束.....")

以上就是python多线程的两种实现方法,大家可以根据具体情况选择不同的实现方法,希望能对你有所帮助哦~

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python多线程的实现方式 https://www.zhiup.top/2909.html

相关