码迷,mamicode.com
首页 > 其他好文 > 详细

Thread其他属性和方法

时间:2018-05-15 10:35:34      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:count   new t   rate   isalive   def   %s   其他   color   new   

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())

技术分享图片

 

Thread其他属性和方法

标签:count   new t   rate   isalive   def   %s   其他   color   new   

原文地址:https://www.cnblogs.com/yaya625202/p/9039035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!