添加線程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)>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章