python threading实现线程的过程

2025-12-01 0 98,311

过程说明

1、从Thread类构成子类。覆盖方法根据需要提供参数。

2、重写线程的业务逻辑。

3、新的Thread子类一旦被定义,就必须对其进行实例化,以启动新的线程。

然后,调用方法启动它。最后,它将调用方法来执行业务逻辑。

实例

#Python 多线程示例打印当前日期。
#1. 使用 threading.Thread 类定义子类。
#2. 实例化子类并触发线程。
 
import threading
import datetime
 
class myThread (threading.Thread):
    def __init__(self, name, counter):
        threading.Thread.__init__(self)
        self.threadID = counter
        self.name = name
        self.counter = counter
    def run(self):
        print("nStarting " + self.name)
        print_date(self.name, self.counter)
        print("Exiting " + self.name)
 
def print_date(threadName, counter):
    datefields = []
    today = datetime.date.today()
    datefields.append(today)
    print("{}[{}]: {}".format( threadName, counter, datefields[0] ))
 
# 创建新线程
thread1 = myThread("Thread", 1)
thread2 = myThread("Thread", 2)
 
# 启动新线程
thread1.start()
thread2.start()
 
thread1.join()
thread2.join()
print("nExiting the Program!!!")

以上就是python threading实现线程的过程,希望对大家有所帮助。更多Python学习指路:python基础教程

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

收藏 (0) 打赏

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

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

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

ZhiUp资源网 python基础 python threading实现线程的过程 https://www.zhiup.top/1054.html

相关