2.创建threading模块中的Thread类实现多线程
这个模块是高层模块,使用起来相对于thread模块更方便一些。
先实例化一个Thread对象,传入work_one和work_two函数,在调用start方法,启动线程。最后用join方法,等待线程退出。
import threading
from time import sleep
def work_one():
print 'John starts to work!\n'
sleep(4) #模拟工作过程
print 'John done his work!\n'
def work_two():
print 'Billy starts to work!\n'
sleep(6) #模拟工作过程
print 'Billy done his work!\n'
def main():
print '***** main *****\n'
thread1=threading.Thread(target=work_one) #创建一个Thread实例
thread2=threading.Thread(target=work_two)
thread1.start() #start函数,启动线程
thread2.start()
thread1.join() #join函数,用于等待线程结束
thread2.join()
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
3.继承Thread类,创建子类实例
编写一个MyThread类,继承,并覆盖run方法。然后再调用start和join方法。
import threading
from time import sleep
class Mythread(threading.Thread):
def __init__(self,time,name):
threading.Thread.__init__(self)
self.time=time
self.name=name
def run(self):
sleep(self.time) #模拟工作过程
def main():
print '***** main *****'
thread1=Mythread(4,'John') #创建一个Thread实例
thread2=Mythread(6,'Billy')
print thread1.name,'starts to work!'
thread1.start() #start函数,启动线程
print thread2.name,'starts to work!'
thread2.start()
thread1.join() #join函数,用于等待线程结束
print thread1.name,'done his work!'
thread2.join()
print thread2.name,'done his work!'
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
效果图如下:

