源码建站教程,销售网站开发意义,最新国际足球世界排名,简单建站的网站视频版教程 Python3零基础7天入门实战视频教程
我们可以使用threading模块的Thread类的构造器来创建线程
def _ init _(self, groupNone, targetNone, nameNone, args(), kwargsNone, *, daemonNone):
上面的构造器涉及如下几个参数。 group:指定该线程所属的线程组。目前该…视频版教程 Python3零基础7天入门实战视频教程
我们可以使用threading模块的Thread类的构造器来创建线程
def _ init _(self, groupNone, targetNone, nameNone, args(), kwargsNone, *, daemonNone):
上面的构造器涉及如下几个参数。 group:指定该线程所属的线程组。目前该参数还未实现因此它只能设为None。 target:指定该线程要调度的目标方法。 name:线程名称一般不用设置 args:指定一个元组以位置参数的形式为 target 指定的函数传入参数。元组的第一个元素传给target函数的第一个参数元组的第二个元素传给target函数的第二个参数……依此类推。 kwargs:指定一个字典以关键字参数的形式为target 指定的函数传入参数。 daemon:指定所构建的线程是否为后代线程。
我们看下实例
import timedef wishing():while True:print(洗菜菜...啦啦啦)time.sleep(1)def cooking():while True:print(烧饭烧菜...啦啦啦)time.sleep(1)if __name__ __main__:wishing()cooking()运行输出的一直是洗菜。
如果我们不用多线程无法实现两个任务一起执行。
我们使用多线程实现代码
import threading
import timedef wishing():while True:print(洗菜菜...啦啦啦)time.sleep(1)def cooking():while True:print(煮饭烧菜...啦啦啦)time.sleep(1)if __name__ __main__:# 创建洗菜线程wishing_thread threading.Thread(targetwishing)# 创建煮饭烧菜线程cooking_thread threading.Thread(targetcooking)# 启动线程wishing_thread.start()cooking_thread.start()传参
import threading
import timedef wishing(msg):while True:print(msg)time.sleep(1)def cooking(msg):while True:print(msg)time.sleep(1)if __name__ __main__:# 创建洗菜线程wishing_thread threading.Thread(targetwishing, args(洗菜菜...啦啦啦,))# 创建煮饭烧菜线程cooking_thread threading.Thread(targetcooking, kwargs{msg: 煮饭烧菜...啦啦啦})# 启动线程wishing_thread.start()cooking_thread.start()