#-*-coding:utf-8-*-import threading #创建多线程(thread二次封装)from time import ctime,sleepimport timedef listen(name): print (‘begin listening to {name} {time}‘.format(name=‘shabi‘,time=ctime()))#类似html的变量,ctime 时间转换成字符串 time.sleep(3) print (‘over {time}‘.format(name=‘shabi‘,time=ctime())) def func(name): print (‘{name} running.{time}‘.format(name=name,time=ctime())) time.sleep(5) print (‘{name} running over.{time}‘.format(name=name,time=ctime())) t1=threading.Thread(target=listen,args=(‘egon‘,)) #实例化,target执行线程名即函数,args传的参数,要以元祖的形式t2=threading.Thread(target=func,args=(‘alex‘,))print (‘game over {time}‘.format(time=ctime()))#主线程必须放在分支线程的start执行前# t1.start()# t2.start()t1.join()#主线程必须等待线程t1执行完threads=[] #通过列表添加顺序for循环,控制执行顺序,但不能决定谁先执行完threads.append(t2)threads.append(t1)for i in threads: i.start()#执行命令内部函数
原文地址:https://www.cnblogs.com/qlshao/p/7855974.html
时间: 2024-10-13 19:46:11