zoukankan      html  css  js  c++  java
  • 19.python设置单线程和多线程

    1.单线程实例:
    代码如下:
    
    from time import ctime,sleep
    def music(A):
        for i in range(2):
            print ("I was listening to %s. %s" % (A, ctime()))
            sleep(1)
    
    def eat(B):
        for i in range(2):
            print ("I was eating the %s! %s" % (B, ctime()))
            sleep(5)
    
    if __name__ == '__main__':
        music('一百万种可能')
        eat('apple')
        print("all over %s" % ctime())
    2.多线程实例:
    代码如下:
    
    from time import ctime,sleep
    import threading
    
    def music(A):
        for i in range(2):
            print("I was listening to %s. %s" % (A, ctime()))
            sleep(1)
    
    def eat(B):
        for i in range(2):
            print("I was eating the %s! %s" % (B,ctime()))
            sleep(5)
    
    threads = []
    th1 = threading.Thread(target=music, args=('That Girl',))
    threads.append(th1)
    th2 = threading.Thread(target=eat, args=('apple',))
    threads.append(th2)
    
    if __name__ == '__main__':
    
        for thread in threads:
            # 设置守护进程
            thread.setDaemon(True)
            thread.start()
        # 等待线程中止,在子线程完成运行之前,这个子线程的父线程将一直被阻塞
        thread.join()
        print('all over %s' % ctime())
  • 相关阅读:
    c# 执行windows模拟登录
    c#文件压缩解压
    c#文件上传下载功能实现
    .NET core3.1 使用Jwt保护api
    我所理解的闭包
    数组遍历for forEach for..in for..of
    变量提升
    微信小程序做radio,可以拖动进度条
    css:flex
    css常用布局
  • 原文地址:https://www.cnblogs.com/lvjing/p/9850159.html
Copyright © 2011-2022 走看看