并发的多线程演示
import threading import time def run() print('你好') time.sleep(2) t1=threading.Thread(target=run,args=('t1',)) t2=threading.Thread(target=run.args=('t2',)) t1.start() t2.start()
继承式调用
import threading import time class MyThread(threading.Thread): def __init__(self,n): super(MyThread,self).__init__() self.n = n def run(self): print('runnint task',self.n) t1=MyThread('t1') t2=MyThread('t2') t1.start() t2.start()
mport threading import time def run(n): print('task',n) time.sleep(2) print('task done',n) start_time=time.time() t_jobs=[] #存线程实例 for i in range(50): t =threading.Thread(target=run,args=('t-%s' %i,)) t.start() t_jobs.append(t) #为了不在这里阻塞后面线程的启动,先把t放到一个列表里面 for t in t_jobs: t.join() #等待线程执行完成后 print('----------all threads has finished') print('coast:',time.time()-start_time)
守护线程,当把所有的子线程设置为守护线程后,当主程序退出后,所有的子线程也就自动退出(不会管子线程有没有执行完毕)
import threading import time def run(n): print('task',n) time.sleep(2) print('task done',n) #start_time=time.time() t_objs=[] for i in range(50): t =threading.Thread(target=run,args=('t-%s' %i,)) t.setDaemon(True) t.start() t_objs.append(t) print('----------all threads has finished')
信号量:允许多个线程同时修改数据
import threading import time def run(n): semaphore.acquire() time.sleep(1) print('run the thread:%s\n' %n) semaphore.release() if __name__ == '__main__': semaphore = threading.BoundedSemaphore(5)#最多允许5个线程同时允许 for i in range(22): t = threading.Thread(target=run,args=(i,)) t.start() while threading.active_count( ) != 1: pass else: print('------all threads done')
本章博客由作者刘少辉著写