# 创建类的线程 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()