入门案例
1 import threading,time 2 ‘‘‘ 3 #线程的创建有两种方式,1.直接调用,2.继承 4 ‘‘‘ 5 # def run(n): 6 # print(‘test‘,n) 7 # #1.直接调用 8 # t1 = threading.Thread(target=run,args=(1,)) 9 # t2 = threading.Thread(target=run,args=(2,)) 10 # t1.start() 11 # t2.start() 12 # #2.继承 13 # class Mythread(threading.Thread): 14 # def __init__(self,n): 15 # super(Mythread,self).__init__() 16 # self.n = n 17 # def run(self): 18 # print(‘test‘,self.n) 19 # t1 = Mythread(1) 20 # t2 = Mythread(2) 21 # t1.start() 22 # t2.start() 23 #统计多个线程耗时,考虑到线程的并发执行,所以每个线程各自指向各自的,主线程执行完后会自动结束,并发执行的时间统计思路就是在线程执行后使用jion()方法,类似于java的wait() 24 def run(n): 25 print(‘thread-‘,n)
#为了更加直观的看到多线程执行的效果,我们使用sleep方法 26 time.sleep(2) 27 start_time = time.time() 28 t_list = [] 29 for i in range(50): 30 t = threading.Thread(target=run,args=(‘{}‘.format(str(i)),)) 31 t.start() 32 t_list.append(t) 33 for j in t_list: 34 j.join() 35 end_time = time.time() 36 print(‘cost time = ‘,end_time - start_time)