python多线程实践

python使用的线程:threading

python多线程的主要函数:

join() 用于等待线程终止。子线程完成运行之前,这个子线程的父线程将一直被阻塞。就是说先运行完被join的线程,再执行别的线程

setDaemon() 将线程声明为守护线程,必须在start() 方法调用之前设置。就是说程序运行的时候不用考虑守护线程是否执行完成,整个程序就能结束。

import time
import threading


def foo():
    Thread_name = threading.current_thread()
    for i in range(2):
        print('This Thread is %s,start时间是:%s' %(Thread_name,time.ctime()))
        time.sleep(2)
        print('This Thread is %s,stop时间是:%s' % (Thread_name,time.ctime()))

def bar():
    Thread_name = threading.current_thread()
    for i in range(2):
        print('This Thread is %s,start时间是:%s' %(Thread_name,time.ctime()))
        time.sleep(3)
        print('This Thread is %s,stop时间是:%s' % (Thread_name, time.ctime()))

def hello(args):
    print('测试线程传递参数,线程名称为:%s' % threading.current_thread())
    time.sleep(3)
    print('传递的参数是%s' % args)

ThreadsList = []

t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=bar)
t3 = threading.Thread(target=hello,args=('测试',)) #后面的参数是元组的形式

ThreadsList.append(t1)
ThreadsList.append(t2)
ThreadsList.append(t3)

if __name__ == '__main__':
    
    for i in ThreadsList:
        i.setDaemon(True) ##守护线程,相当于不用等待t1,t2,t3执行完成就可以结束程序
        i.start()
        # i.join() #join优先保证这个线程执行完成,相当于保证t1,t2,t3都执行晚,再执行别的进程
    # i.join() #这个地方的i,相当于for循环中的t3

    print("This is main Thread")
原文地址:https://www.cnblogs.com/aniuzaixian/p/8116365.html