python 多线程
今日使用库——threading
今日参考文章:菜鸟教程——python多线程
1. 首先创建一个类
class MyThread(threading.Thread):
def __init__(self, thread_id, name, speed):
threading.Thread.__init__(self)
# 线程 id
self.thread_id = thread_id
# 线程 名称
self.name = name
# 线程执行速度
self.speed = speed
# run 方法
def run(self) -> None:
print("线程执行: [id-", self.thread_id, ",名称:", self.name, "]")
print_time(self.name, self.speed)
print("线程结束: [id-", self.thread_id, ",名称:", self.name, "]")
在 run 方法中,就是线程执行的...
可以将 run 方法看作 主程序的 main 方法
2. 创建类的实例
thread1 = MyThread(1, "线程1", 2)
thread2 = MyThread(2, "线程2", 1)
运行效果:
3. 总体代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
class MyThread(threading.Thread):
def __init__(self, thread_id, name, speed):
threading.Thread.__init__(self)
# 线程 id
self.thread_id = thread_id
# 线程 名称
self.name = name
# 线程执行速度
self.speed = speed
# run 方法
def run(self) -> None:
print("线程执行: [id-", self.thread_id, ",名称:", self.name, "]")
print_time(self.name, self.speed)
print("线程结束: [id-", self.thread_id, ",名称:", self.name, "]")
def print_time(thread_name, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("{} : {}".format(thread_name, time.ctime(time.time())))
# 创建线程
thread1 = MyThread(1, "线程1", 2)
thread2 = MyThread(2, "线程2", 1)
thread1.start()
thread2.start()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!