-
python 多线程基础
通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法- 常用的函数说明
run(): 用以表示线程活动的方法。
start():启动线程活动。
join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
sAlive(): 返回线程是否活动的。
getName(): threading.current_thread().getName() 返回线程名。
setName(): 设置线程名。
- 常用的函数说明
-
创建线程
- 导入线程模块 import threading
import threading
import time
def mythread(arg):
while True:
print("the time is %s" % time.ctime())
time.sleep(1)
t=threading.Thread(target=mythread,args=(10,)) #创建一个线程,args 这里为元组形式,10后面必须以逗号分隔结束,target 此处调用线程无需添加括号
t.daemon=True
t.start()
- 创建线程,并发执行
# 创建数组存放线程
threads = []
for i in range(1):
t = threading.Thread(target=Test_case.test_interface, args=()) # 设置线程数据
t1=threading.Thread(target=Test_case.reverse_post,args=())
threads.append(t)
threads.append(t1)
print('The Test Start:', ctime())
if __name__ == '__main__':
# 线程启动方法
for i in threads:
i.start()
for i in threads:
i.join()
#直接调用函数法
#Test_case.test_interface()
print('The Test End:', ctime())