python,通过创建类实现多线程例子
import threading,time class MyThread(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num = num def run(self): print("running on number:%s"%self.num) time.sleep(self.num) if __name__ == '__main__': begin = time.time() t1 = MyThread(1) t2 = MyThread(2) t1.start() t2.start() t1.join() t2.join() end = time.time() print(end - begin)
程序执行结果:
running on number:1
running on number:2
2.0025267601013184
Process finished with exit code 0
t.start()方法自动调用类中的run()方法,所以在实现的时候只需要将自己的任务代码写在run()方法中即可.