多线程(Threading)

添加线程

添加线程,需要使用threading.Thread()方法,参数为线程函数和线程函数的参数
threading.Thread(target=线程函数, args=(线程函数的参数,))
1、导入threading模块
2、定义线程函数
3、创建线程对象
4、启动线程

1
2
3
4
5
6
7
8
9
import threading
def thread_job():
print(f'This is an added thread, number is {threading.current_thread()}')
def main():
added_thread = threading.Thread(target=thread_job) # 添加线程,还要给线程一个工作,target = 功能(定义一个函数来表示这个是来做什么的)
added_thread.start() # 启动线程

if __name__ == '__main__':
main()

5、获取当前线程数和所有线程名

1
2
3
4
5
6
7
8
import threading
def main():
print(threading.active_count()) # 获取当前线程数
print(threading.enumerate()) # 获取当前所有线程名
print(threading.current_thread()) # 获取当前运行程序的线程

if __name__ == '__main__':
main() #