python 启动线程的两种方法

版权声明:随便转载,互相学习,注明来源即可,不想注明也没事 https://blog.csdn.net/yangwohenmai1/article/details/86679649

Python调用线程有两种情况,一种是在主线程中直接调用,还一种是直接在其他方法中调用线程

在传递参数的方式上有所区别,两种调用方法如下:

1. 主进程中直接调用线程:

from threading import Thread
import 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)







猜你喜欢

转载自blog.csdn.net/yangwohenmai1/article/details/86679649