zoukankan      html  css  js  c++  java
  • Thread其他属性和方法

    1、查看修改线程名称

    currentThread().getName()

    from threading import Thread,currentThread
    import time
    
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done",currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task)
        t.start()
        print("The main name:",currentThread().getName() )

    参数name对线程名称进行修改

    from threading import Thread,currentThread
    import time
    
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done" % currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task,name="The new Thread")
        t.start()
        print("The main name:",currentThread().getName())

    “子”线程设置线程名称:t.setName(NewName)

    “主”线程设置线程名称,先拿到主线程,在调用setName方法

    from threading import Thread,currentThread
    import time
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done" % currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task,name="The new Thread")
        t.start()
        t.setName("New Name")
        currentThread().setName("Main new name")
        print("The main name:",currentThread().getName())

    2、查看线程是否存活t.isAlive()或者t.is_alive()

    from threading import Thread,currentThread
    import time
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done" % currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task,name="The new Thread")
        t.start()
        # t.is_alive()
        print(t.isAlive())
        print("The main name:",currentThread().getName())

     3、查看线程存活数量active_count

    from threading import Thread,currentThread,active_count
    import time
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done" % currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task,name="The new Thread")
        t.start()
        # t.is_alive()
        print(active_count())

    4、拿到活跃的线程对象enumerate

    from threading import Thread,currentThread,enumerate
    import time
    def task():
        print("%s is running" % currentThread().getName())
        time.sleep(2)
        print("%s is done" % currentThread().getName())
    if __name__ == "__main__":
        t=Thread(target=task,name="The new Thread")
        t.start()
        print(enumerate())

  • 相关阅读:
    ecshop中关于语言配置项的管理
    ecshop中猜你喜欢的原理
    CSS之Position详解(自cnblogs)
    包装类
    for循环的另一种写法
    date.calendar学习总结
    java对MySql数据访问
    java中对MySql的配置
    小程序在js里获取控件的两种方式
    样式一直没生效,发现css没加前面的小点!!!
  • 原文地址:https://www.cnblogs.com/yaya625202/p/9039035.html
Copyright © 2011-2022 走看看