python之路——多线程
1、多线程模块 import threading
2、用函数写一个多线程例子
import threading,time def talk(name): print(name,"is tlaking",threading.current_thread(),threading.active_count()) time.sleep(2) print("thread done ....",name) p1 = threading.Thread(target=talk,args = ("alex",)) p2 = threading.Thread(target=talk,args = ("japhi",)) p1.start() p2.start()
结果是:
alex is tlaking <Thread(Thread-1, started 5680)> 2 japhi is tlaking <Thread(Thread-2, started 4592)> 3 thread done .... alex thread done .... japhi
其中threading.current_thread() 用来打印当前的线程,threading.active_count()打印线程数,结果是一起运行。
3、用面向对象的方式写一个多线程
import threading,time class Mythread(threading.Thread): def __init__(self,name): super(Mythread,self).__init__() self.name = name def run(self): #必须是run print(self.name,"is tlaking") time.sleep(2) p3 = Mythread("alex") p4 = Mythread("japhi") p3.start() p4.start()
但是,面向对象的形式中的方法名必须是run
4、join()方法
join方法是指当前线程执行完才能继续执行下一个线程,代码示例
import threading,time start_time = time.time() def talk(name): print(name,"is tlaking",threading.current_thread(),threading.active_count()) time.sleep(2) print("thread done ....",name) p1 = threading.Thread(target=talk,args = ("alex",)) p2 = threading.Thread(target=talk,args = ("japhi",)) p1.start() p1.join() p2.start() print("cost:",time.time() - start_time)
结果是:
先打印:alex is tlaking <Thread(Thread-1, started 3444)> 2 2秒后。。。 打印:thread done .... alex japhi is tlaking <Thread(Thread-2, started 11988)> 2 cost: 2.0001144409179688 2秒后打印:thread done .... japhi
等1线程执行完后才执行线程2
4、以一个循环的例子:
import threading,time start_time = time.time() def talk(name): print(name,"is tlaking",threading.current_thread(),threading.active_count()) time.sleep(2) print("thread done ....",name) res = [] for i in range(10): p1 = threading.Thread(target=talk,args = (i,)) #多线程并发,target是任务,args是参数,参数后面一定要加, p1.setDaemon(True) # 把当前线程变为守护线程 p1.start() res.append(p1) for obj in res: obj.join() print("cost:",time.time() - start_time)
计算10个线程都结束后花的时间,结果是cost: 2.0021145343780518
5、守护线程
t.setDaemon(True) 将t这个线程设为守护线程,主线程代码结束后不会等t线程是否结束,直接退出程序
import threading,time start_time = time.time() def talk(name): print(name,"is tlaking",threading.current_thread(),threading.active_count()) time.sleep(2) print("thread done ....",name) for i in range(10): p1 = threading.Thread(target=talk,args = (i,)) #多线程并发,target是任务,args是参数,参数后面一定要加, p1.setDaemon(True) # 把当前线程变为守护线程 p1.start() print("cost:",time.time() - start_time)
结果是: