python中怎么调用线程
Python调用线程有两种情况,一种是在主线程中直接调用,还一种是直接在其他方法中调用线程
在传递参数的方式上有所区别,两种调用方法如下
1. 主进程中直接调用线程:
from threading import Threadimport time
def sayhi(name,input,number):
for i in range(1,10):
if number == "线程号1":
time.sleep(2)
print("这是线程号:%s - %s say hello %s - %s" % (number,name, str(i),input))
else :
time.sleep(1)
print("线程号:%s - %s say hello %s - %s 休息1秒" % (number,name, str(i),input))
if __name__ == '__main__':
for i in range(1,3):
t = Thread(target=sayhi, args=('mike','to you',"线程号"+str(i) ))
t.start()
print("主线程结束")
2.在方法中调用线程:
在方法中调用线程的时候,如果不想另外写一个class,也不想用self参数,
在写Thread(target=Th2, args=(input,))的时候,记得args数的最后中加一个“逗号”,这样表明你传的是一个数据元组
否则会报“takes 1 positional argument but 2 were given”这种错误,因为传入的参数数量识别时出现了问题
# -*- coding: utf-8 -*-import time
from threading import Thread
def doWork(input):
global interval
try:
print("begin")
if "DERNAV" in input.upper():
t = Thread(target=Th1, args=(input,))
t.start()
elif "PBD9008" in input.upper():
t = Thread(target=Th2, args=(input,))
t.start()
except Exception as e :
print(e)
def Th1(input):
for i in range(1,10):
print(input+"_"+time.strftime('%Y.%m.%d %H:%M:%S'))
time.sleep(1)
def Th2(input):
for i in range(1,10):
print(input+"_"+time.strftime('%Y.%m.%d %H:%M:%S'))
time.sleep(2)
def run(interval):
while True:
try:
doWork("PBD9008")
doWork("DERNAV")
time_remaining = interval - time.time() % interval
time.sleep(time_remaining)
except Exception as e:
print(e)
if __name__ == '__main__':
global interval
interval = 300
text = run(interval)
以上是 python中怎么调用线程 的全部内容, 来源链接: utcz.com/z/525540.html