多线程——添加线程Thread

1.添加线程

今天我们来学习threading模块的一些基本操作,如获取线程数,添加线程等。首先别忘了导入模块:

import threading

获取已激活的线程数

import threading

def main():
    print(threading.active_count())

if __name__ == "__main__":
    main()
#输出
1

查看所有线程信息

import threading

def main():
    print(threading.enumerate())

if __name__ == "__main__":
    main()
#输出
[<_MainThread(MainThread, started 4790924736)>]

显示当前线程

import threading

def main():
    #print(threading.active_count())
    #print(threading.enumerate())
    print("currnet thread :",threading.current_thread())
if __name__ == "__main__":
    main()

添加线程,threading.Thread()接收参数target代表这个线程要完成的任务,需自行定义

import threading

def thread_job():				#python模块中的一个功能
    print('This is a thread of %s' % threading.current_thread())

def main():
    thread = threading.Thread(target=thread_job,)   # 定义线程,并且把功能传进去
    thread.start()  # 让线程开始工作
    #print(threading.active_count())
    print(threading.enumerate())
    #print("currnet thread :",threading.current_thread())
if __name__ == '__main__':
    main()
#输出
This is an added Thread,number is <function current_thread at 0x10f7a08c0>
[<_MainThread(MainThread, started 4748305856)>, <Thread(Thread-1, started 123145447149568)>]

2.完整代码

import threading

def thread_job():
    print("This is an added Thread,number is %s" % threading.current_thread)

def main():
    added_thread = threading.Thread(target = thread_job)
    added_thread.start()
    print(threading.active_count())
    print(threading.enumerate())
    print("currnet thread :",threading.current_thread())
    
if __name__ == "__main__":
    main()

输出

This is an added Thread,number is <function current_thread at 0x1089f48c0>
2
[<_MainThread(MainThread, started 4573492672)>]
currnet thread : <_MainThread(MainThread, started 4573492672)>
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值