import time import threading def sing(): for i in range(0,5): print("正在唱歌") time.sleep(1) def dance(): for i in range(0,5): print("正在跳舞") time.sleep(1) def main(): #create a thread t1=threading.Thread(target=sing) t2=threading.Thread(target=dance) t1.start() t2.start() #打印线程名字 print(threading.enumerate()) if __name__ == "__main__": main()
import time import threading def sing(): for i in range(0,5): print("正在唱歌") # time.sleep(1) def dance(): for i in range(0,5): print("正在跳舞") # time.sleep(1) def eat(): print("eat......") def main(): for i in range(5): t=threading.Thread(target=eat) t.start() if __name__ == "__main__": main()
import threading import time class MyThread(threading.Thread): #必须要有run方法 def run(self):#这个函数的名字必须是run for i in range(3): time.sleep(3) msg = "haha" print(msg) if __name__ == "__main__": t=MyThread() t.start()#他会自动的去找run函数里面的方法,run函数的名字是固定的 #没有定义start方法,却可以用,因为start是继承Thread类的方法,调用了start的方法之后会自动执行run方法