python-多线程趣味
假设一个程序员,想听歌,但是又想敲代码,于是又:
我听完歌就去敲代码:
#! /usr/bin/env python #coding=utf-8 import time def matter1(music): print("我想听这些歌") for i in range(0,len(music)): print("第" + str(i + 1) + "首歌是:" + str(music[i])) #当前时间 print(time.strftime('%Y%H%M%S',time.localtime())) #假设每一首歌曲的时间是2秒 time.sleep(2) print("切换下一首歌...") def matter2(number): print("我在敲代码") j = 0 while j < number: print("我准备写入第" + str(j +1) + "行代码") j = j + 1 #当前时间 print(time.strftime('%Y%H%M%S',time.localtime())) #假设每写一行代码的时间为1s time.sleep(1) print("写下一行代码...") if __name__ == '__main__': start = time.time() #设定我要听的个为 music = ['music1','music2','music3'] #开始听歌 matter1(music) #设定敲代码的行数 number = 5 #开始敲代码 matter2(number) end = time.time() print("完成的时间:",str(end - start))
结果:
完成的时间: 11.00062894821167
可以改成,一边敲代码一边听歌,那么设计一个多线程,可以让他们同时进行
#! /usr/bin/env python #coding=utf-8 import time import threading def matter1(music): print("我想听歌!!!") for i in range(0,len(music)): print("第" + str(i+1) + "首歌是:" + str(music[i])) #当前时间是 print(time.strftime('%Y%H%M%S',time.localtime())) #假设每一首歌曲的时间是2s time.sleep(2) print("切换下一首歌...") def matter2(number): print("我在敲代码!!!") j = 0 while j < number: print("我准备写入第" + str(j+1) + "行代码") j = j+1 #当前时间是 print(time.strftime('%Y%H%M%S',time.localtime())) #假设每写一行代码的时间为1s time.sleep(1) print("写下一行代码...") if __name__ == '__main__': #设定我要听的歌为 music = ["music1","music2","music3"] #设定我要敲代码的行数 number = 5 threads = [] thing1 = threading.Thread(target=matter1,args=(music,)) threads.append(thing1) thing2 = threading.Thread(target=matter2,args=(number,)) threads.append(thing2) #开始时间 startTime = time.time() #写个for让两件事情都进行 for thing in threads: #setDaemon为主线程启动了线程matter1和matter2 #启动也就是相当于执行了这个for循环 thing.setDaemon(True) thing.start() #为了防止子线程还没结束主线程就结束的意外情况,在程序里面加个join #子进程没结束前,主线程会被卡在这里 thing1.join() thing2.join() #结束时间 endTime = time.time() print("完成的时间为:",str(endTime-startTime))
结果:
完成的时间为: 6.000343084335327
封装成类的形式
#! /usr/bin/env python #coding=utf-8 import time import threading class MyThread(threading.Thread): def __init__(self,func,args,name=''): threading.Thread.__init__(self) self.name = name self.func = func self.args = args def run(self): #某某线程要开始了 print(self.name + "开始了#######") if self.name == "听歌线程": matter1(music) elif self.name == "打码线程": matter2(number) print(self.name + "结束了########") def matter1(music): for i in range(0,len(music)): print("第" + str(i+1) + "首歌是:" + str(music[i])) #假设每一首歌曲的时间是2s time.sleep(2) print("切换下一首歌...") def matter2(number): j = 0 while j < number: print("我准备写入第" + str(j+1) + "行代码") j = j+1 #假设每一行代码的时间为1s time.sleep(1) print("写下一行代码...") if __name__ == '__main__': #设定我要听的歌曲为 music = ['music1','music2','music3'] #设定我要打码的行数 number = 5 #开始时间 start = time.time() thing1 = MyThread(matter1,music,"听歌线程") thing2 = MyThread(matter2,number,"打码线程") thing1.start() thing2.start() thing1.join() thing2.join() #结束时间 end = time.time() print("完成的时间为:",str(end - start))
结果:
完成的时间为: 6.001343011856079