# 創建類的線程 import threading import time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "我是[線程]" + self.name + '... ...
# 創建類的線程 import threading import time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "我是[線程]" + self.name + '@' + str(i) print(msg) if __name__ == "__main__": t = MyThread() t.start() # run會被自動調用,可在run中調用其他自定義類方法
# 創建函數的線程 import threading import time def func1(): for i in range(5): time.sleep(1) print("func1---%d" % i) def func2(): for i in range(10): time.sleep(1) print("func2---%d" % i) def main(): t1 = threading.Thread(target=func1) t2 = threading.Thread(target=func2) while True: # 查看當前有多少線程 print(threading.enumerate()) time.sleep(1) if __name__ == "__main__": main()