zoukankan      html  css  js  c++  java
  • Python多线程threading的使用

    一. threading的参数传递,参数之后的’,‘不能少,此处的’,‘是用来区分此参数作为元组(包含多个参数)来传递的,而不是单个参数传递

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        #time.sleep(3)
        print("I'm C")
    
    print(a())

    二. sleep的位置很重要,如上输出结果:

    I'm A
    I'm MainThread
    I'm C
    None
    I'm B
    I'm LoopThread
    I'm test
    I'm sleep after

    第二种情况:

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        #time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        #time.sleep(3)
        print("I'm C")
    
    print(a())

    输出结果:

    I'm A
    I'm BI'm
    I'm  LoopThread
    I'm test
    MainThread
    I'm C
    None
    I'm sleep after

    第三种情况:

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        #time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        time.sleep(3)
        print("I'm C")
    
    print(a())

    输出结果:

    I'm A
    I'm BI'm
     MainThread
    I'm LoopThread
    I'm test
    I'm sleep after
    I'm C
    None

    似乎其中一个线程稍微阻塞(或睡眠)就会立马开始执行另外一个,可以据此调控两个线程的交替?

    关于线程的参数传递需要注意

  • 相关阅读:
    set集合操作
    python中字符串操作
    字典----增删改查遍历
    C#反射回顾笔记
    消息队列之ActiveMQ学习笔记(二、C#实例实现)
    消息队列之ActiveMQ学习笔记(一、下载及安装)
    依赖注入之AutoFac
    layer弹框层学习笔记
    VS自定义代码块Code Snippet
    博客园添加链接
  • 原文地址:https://www.cnblogs.com/sen-c7/p/9475245.html
Copyright © 2011-2022 走看看