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() # 启动线程 t1 ;
t2.start() # 启动线程 t2 ;
t1.join() # 等待线程 t1 结束;
t2.join() # 等待线程 t2 结束;
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): # run方法是默认执行的,不能改名字;
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()