python多线程

创建多线程的方法

1.通过_threads模块创建多线程(了解即可):

import _thread
import time
def speak():
print('去你大爷')
def main():#创建线程函数
_thread.start_new_thread(speak,())
_thread.start_new_thread(speak,())#创建两个线程
time.sleep(1)#线程暂停时间为1s
if __name__ == '__main__':
main()

 

>>>去你大爷去你大爷

2.通过threading模块中Thread类的实例化对象创建多线程

import threading
def speak():
print('去你大爷')
def main():#创建线程函数
for i in range(5):
t=threading.Thread(target=speak,args=())
t.start()
t.join()


if __name__ == '__main__':
main()

>>>

去你大爷
去你大爷
去你大爷
去你大爷
去你大爷

3.通过继承Thread类重写run方法创建线程对象

import threading
class mythread(threading.Thread):
def __init__(self,n):
super(mythread, self).__init__()
self.n=n
def run(self):
print('%s'%(self.n))
def main():
threads=[]
threads_count=5
for i in range(threads_count):
t=mythread('去你大爷'+str(i))
threads.append(t)
for i in range(threads_count):
threads[i].start()
for i in range(threads_count):
threads[i].join()


if __name__ == '__main__':
main()
》》》

去你大爷0
去你大爷1
去你大爷2
去你大爷3
去你大爷4

posted @ 2020-09-03 22:56  bsde  阅读(197)  评论(0)    收藏  举报