多线程举例:
import time import threading def worker(): print ("hello.Kamil") time.sleep(1)#等待一秒 return time_start=time.time() if __name__ == "__main__": for i in range(5): worker()#(执行五次) time_end = time.time() print(time_end-time_start) for n in range(5): t = threading.Thread(target=worker) t.start() time_end2 = time.time()
执行结果:
[email protected]:~/PycharmProjects/ftp0310/0310shangke/try$ python3.4 d.py hello.Kamil hello.Kamil hello.Kamil hello.Kamil hello.Kamil 5.006033897399902 hello.Kamil hello.Kamil hello.Kamil hello.Kamil hello.Kamil 0.0030531883239746094 [email protected]-kamil:~/PycharmProjects/ftp0310/0310shangke/try$
第二次虽然也是循环5次,但是启用多线程来完成的,所以速度提升非常明显;
示例2:
import threading import time class timer(threading.Thread): def __init__(self, num, interval): threading.Thread.__init__(self) self.thread_num = num self.interval = interval self.thread_stop = False def run(self): while not self.thread_stop: print (‘Thread Object(%s), Time:%s\n‘ %(self.thread_num, time.ctime()) ) time.sleep(self.interval) def stop(self): self.thread_stop = True def test(): thread1 = timer(‘thread1‘,2) thread2 = timer(‘thread2‘,3) thread1.start() thread2.start() time.sleep(7) thread1.stop() thread2.stop() return if __name__ == ‘__main__‘: test()
同时启动两个线程,thread1 与 thread2 ,其中1 是间隔2s 执行打印一次,2是间隔3s执行打印一次;在运行开始后,会在第六秒再次同时运行;结果如下:
[email protected]:~/PycharmProjects/ftp0310/0310shangke/try$ python3.4 c.py Thread Object(thread1), Time:Thu Mar 17 09:27:26 2016 1 26 Thread Object(thread2), Time:Thu Mar 17 09:27:26 2016 2 26 Thread Object(thread1), Time:Thu Mar 17 09:27:28 2016 1 28 Thread Object(thread2), Time:Thu Mar 17 09:27:29 2016 2 29 Thread Object(thread1), Time:Thu Mar 17 09:27:30 2016 1 30 Thread Object(thread2), Time:Thu Mar 17 09:27:32 2016 2 32 Thread Object(thread1), Time:Thu Mar 17 09:27:32 2016 1 32 [email protected]-kamil:~/PycharmProjects/ftp0310/0310shangke/try$
时间: 2024-10-04 00:16:38