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()