刚刚学习了Python的多线程,为了测试多线程对处理数据的影响,自己写了一个简单的实例实践一下多线程:
# -*- coding:utf-8 -*-
#Python多线程实例
import threading
import datetime
import time
def handleUrlListA():
'''
线程A:如果有数据就处理,否则就等待
:return:
'''
global urlListA
global flagA
while True:
if len(urlListA) > 0:
print(urlListA[len(urlListA) - 1])
time.sleep(0.5)
urlListA.pop()
elif len(urlListA) == 0 and flagA == True:
break
def handleUrlListB():
'''
线程B:如果有数据就处理,否则就等待
:return:
'''
global urlListB
global flagB
while True:
if len(urlListB) > 0:
print(urlListB[len(urlListB) - 1])
time.sleep(0.5)
urlListB.pop()
elif len(urlListB) == 0 and flagB == True:
break
if __name__ == "__main__":
startTime = datetime.datetime.now()
#全局变量初始化
urlListA = []
urlListB = []
flagA = False
flagB = False
#创建多线程
ta = threading.Thread(target=handleUrlListA, name="threadA")
tb = threading.Thread(target=handleUrlListB, name="threadB")
ta.start()
tb.start()
#运行与结束
for i in range(100):
if i % 2 == 0:
urlListA.append(i)
else:
urlListB.append(i)
flagA = True
flagB = True
# 主线程等到子线程执行完才能结束
ta.join()
tb.join()
endTime = datetime.datetime.now()
print("function execution time(s) is :%s" % (endTime - startTime))
本文是一个特别简单的例子,看了别人写的Python多线程,感觉自己的还是特别的简单,希望向大牛们继续学习!