创建多线程的两种方式:
第一种创建方式:
导入: from threading import Thread,current_thread(当前线程)
def sing(num):
for i in range(num):
print("正在唱歌...%d" % i)
sleep(random())
def dance(num):
for i in range(num):
print("正在跳舞...%d" % i)
sleep(random())
def f1():
Thread(target=sing,args=(randint(5,10),)).start()
Thread(target=dance,args=(randint(5,10),)).start()
if __name__ =='__main__':
f1()
第二种创建方式:
class SingThread(Thread):
def __init__(self,num):
self.num = num
super().__init__()
def run(self):
for i in range(self.num):
print("正在唱歌...%d" % i)
sleep(random())
class DanceThread(Thread):
def __init__(self,num):
self.num = num
super().__init__()
def run(self):
for i in range(self.num):
print("正在tiaowu...%d" % i)
sleep(random())
def f2():
SingThread(randint(5,10)).start()
DanceThread(randint(5,10)).start()
if __name__ =='__main__':
f2()
'多线程修改全局变量'
g_num = 100
def work1():
global g_num
for i in range(3):
g_num += 1
print("----in work1, g_num is %d---"%g_num)
def work2():
global g_num
print("----in work2, g_num is %d---"%g_num)
if __name__ == '__main__':
print("---线程创建之前g_num is %d---"%g_num)
Thread(target=work1).start()
#延时一会,保证t1线程中的事情做完
time.sleep(1)
Thread(target=work2).start()
’查看线程的数量‘
while True:
# 统计当前进程里有哪些线程在运行
ts = threading.enumerate()
length = len(ts)
print('当前运行的线程数为:%d,names=%s'%(len(ts),[i.name for i in ts]))
if length<=1:
break