• 多线程示例


    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    # @Time    : 2018/6/26 14:36
    # @File    : 多线程.py

    import threading
    from time import ctime, sleep


    def music(name):
        for i in range(2):
            print("I was listening to music . %s %s" % (name, ctime()))
            sleep(4)


    def coding(code):
        for i in range(2):
            print("I was coding codes! %s %s" % (code, ctime()))
            sleep(5)


    threads = []

    # 创建了threads数组,创建线程t1,使用threading.Thread()方法,
    # 在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。
    # 定义单元素的tuple有歧义,所以 Python 规定,单元素 tuple 要多加一个逗号“,”,这样就避免了歧义:
    t1 = threading.Thread(target=music, args=(u'伟大的闯爷之歌',))
    threads.append(t1)

    # 接着以同样的方式创建线程t2,并把t2也装到threads数组。
    t2 = threading.Thread(target=coding, args=(u'python代码',))
    threads.append(t2)

    if __name__ == '__main__':
        for t in threads:
            # setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。
            # 子线程启动后,父线程也继续执行下去,
            # 当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。
            t.setDaemon(True)
            # 开始线程活动
            t.start()
        t.join()
        print(" all over %s" % ctime())

  • 相关阅读:
    [opentwebst]一个简单的登陆脚本
    opentwebst一个ie自动化操作测试软件-功能强大
    给X9DRL-iF双路服务器主板刷BIOS
    在ubuntu16下面通过kvm+lvm安装ubuntu16的虚拟机
    ubuntu16安装KVM
    PowerShell全自动分配CPU
    在ubuntu16编译安装nginx-1.10.2(full)完全自带组件
    将博客搬至CSDN
    乌邦图ubuntu配置iptables的NAT上网
    LVM增大和减小ext4、xfs分区
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9229889.html
Copyright © 2020-2023  润新知