import threading
import time
两种方式,注意线程的调度时间sleep不要设置太大,越小cpu的使用率就会越高,并行效果越明显!
(1)直接调用threading创建线程
def print_age(who, age):
""" 需要用多线程调用的函数 :param who: :param age: :return: """
print("Hello,every one!")
time.sleep(1)
print("%s is %s years old !" % (who, age))
if __name__ == "__main__":
t1 = threading.Thread(target=print_age, args=("jet", 18, )) # 创建线程1
t2 = threading.Thread(target=print_age, args=("jack", 25, )) # 创建线程2
t3 = threading.Thread(target=print_age, args=("jack", 25,)) # 创建线程3
t1.start() # 运行线程1
t2.start() # 运行线程2
t3.start() # 运行线程3
print("over...")
(2)通过继承重写run方法
import threading
import time
class MyThread(threading.Thread):
""" 使用继承的方式实现多线程 """
def __init__(self, who):
super().__init__() # 必须调用父类的构造方法
self.name = who def run(self): print("%s is run..." % self.name)
time.sleep(3)
if __name__ == "__main__":
t1 = MyThread("Jet") # 创建线程1
t2 = MyThread("Jack") # 创建线程2
t1.start() # 运行线程1
t2.start() # 运行线程2
print("over...")