1、简单使用方法;
import threading
def sing(name): for i in list(range(3)): print("{}-------正在唱歌------".format(name)) time.sleep(1)def dance(name): for i in list(range(3)): print("{}-------正在跳舞------".format(name)) time.sleep(1)def main(): t1 = threading.Thread(target=sing,args=("张三",)) #参数必须是元组,传一个参数时后面加逗号","; t2 = threading.Thread(target=dance,args=("李四",)) #参数必须是元组,传一个参数时后面加逗号",";
t1.start() t2.start()if __name__ == "__main__": main()
2、重写threading.Thread的使用方法;
想创建一个线程对象,只要继承类threading.Thread,然后在__ init__里边调用threading.Thread.__init__()方法即可。
重写run()方法,将要实现的功能放到此方法中即可。
import threading
class MyTestThread(threading.Thread): def __init__(self,name,age): threading.Thread.__init__(self) self.name = name self.age = age def run(self): print("他是:{},今年:{}岁".format(self.name,self.age)) self.sing() self.dance() def sing(self): for i in list(range(3)): print("-------正在唱歌------") time.sleep(1) def dance(self): for i in list(range(3)): print("-------正在跳舞------") time.sleep(1)def main(): t = MyTestThread("张三","18") t.start()if __name__ == "__main__": main()
来源:https://www.cnblogs.com/guoyucong/p/12563506.html