多线程
1、简单例子:
import threading import time def work(n): time.sleep(2) print ("threading :",n) time1 = time.time() t1 = threading.Thread(target=work,args=("alex",)) t2 = threading.Thread(target=work,args = ("kaka",)) t1.start() t2.start() time2 = time.time() print (time2 - time1) 2、用类实现:
class MyThread(threading.Thread): def __init__(self,n): super(MyThread, self).__init__() self.n = n def run(self): print ("run",self.n) a = MyThread("kaka") b = MyThread("wawa") a.run() b.run() -------------------------------------------------------------- 3、主线程启动子线程,子线程独立运行(由原串行变为并行);
import threading import time def work(n): time.sleep(2) print ("threading :",n) start_time = time.time() for i in range(50): t = threading.Thread(target=work,args = ("threading %s" % i,)) t.start() cost = time.time()-start_time print ("耗时%s" % cost) 4、join()
import threading import time def work(n): print ("threading %s is start!" % n) time.sleep(2) print ("threading %s is done!:" % n) start_time = time.time() res_list = [] for i in range(50): t = threading.Thread(target=work,args = ("threading %s" % i,)) t.start() res_list.append(t) for t in res_list:#join相当于wait的意思;等待所有线程结束后,再往下走; t.join() cost = time.time()-start_time print ("耗时%s" % cost) 5、