前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【说站】python threading实现线程的过程

【说站】python threading实现线程的过程

作者头像
很酷的站长
发布2022-11-24 11:27:35
1900
发布2022-11-24 11:27:35
举报
文章被收录于专栏:站长的编程笔记

python threading实现线程的过程

过程说明

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

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

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

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

实例

代码语言:javascript
复制
#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实现线程的过程,希望对大家有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python threading实现线程的过程
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档