例:
#coding=utf-8 import threading import time def saySorry(): print("亲爱的,我错了,我能吃饭了吗?") time.sleep(1) if __name__ == "__main__": for i in range(5): t = threading.Thread(target=saySorry) t.start() #启动线程,即让线程开始执行 结果:
2.继承threading.Thread
#coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字 print(msg) if __name__ == '__main__': t = MyThread() t.start() 结果: 2、查看线程数量 threading.enumerate():显示当前进程所有正在运行的线程 len(threading.enumerate()): 线程数 threading.current_thread():显示当前运行的线程 In [7]: threading.enumerate() Out[7]: [<_MainThread(MainThread, started 140487919113984)>, <HistorySavingThread(IPythonHistorySavingThread, started 140487852594944)>] In [9]: threading.current_thread()Out[9]: <_MainThread(MainThread, started 140487919113984)>
3、多线程-共享全局变量 例:
from threading import Thread import time def work1(nums): nums.append(44) print("----in work1---",nums) def work2(nums): #延时一会,保证t1线程中的事情做完 time.sleep(1) print("----in work2---",nums) g_nums = [11,22,33] t1 = Thread(target=work1, args=(g_nums,)) t1.start() t2 = Thread(target=work2, args=(g_nums,)) t2.start()运行结果:
----in work1--- [11, 22, 33, 44] ----in work2--- [11, 22, 33, 44]4、多线程-非共享数据
例:
#coding=utf-8 import threading import time class MyThread(threading.Thread): # 重写 构造方法 def __init__(self,num,sleepTime): threading.Thread.__init__(self) self.num = num self.sleepTime = sleepTime def run(self): self.num += 1 time.sleep(self.sleepTime) print('线程(%s),num=%d'%(self.name, self.num)) if __name__ == '__main__': mutex = threading.Lock() t1 = MyThread(100,5) t1.start() t2 = MyThread(200,1) t2.start()结果: