Python多執行緒程式設計

2021-10-19 15:20:47 字數 1832 閱讀 6501

import threading

import time

class mythread(threading.thread):

def __init__(self, thread_name):

# 注意:一定要顯式的呼叫父類的初始化函式。

super(mythread, self).__init__(name=thread_name)

def run(self):

time.sleep(1)

print("%s正在執行中......" % self.name)

if __name__ == '__main__':

for i in range(10):

mythread("thread-" + str(i)).start()

執行結果截圖:

t.join() # 子執行緒全部加入,主線程等所有子執行緒執行完畢

執行結果截圖:

t.join()的作用為等待子執行緒執行完畢,執行結果截圖,變成單執行緒執行結果:

注意下方例項化執行緒物件的引數與方法二中第乙個程式的區別,其執行結果仍舊是單執行緒的執行結果

import threading

import time

def show(arg):

time.sleep(1)

print('thread '+str(arg)+" running....")

if __name__ == '__main__':

thread_list =

for i in range(10):

t = threading.thread(target=show(i))

t.start()

for t in thread_list:

t.join() # 子執行緒全部加入,主線程等所有子執行緒執行完畢

python 多執行緒程式設計

一 執行緒基礎 1 建立執行緒 thread模組提供了start new thread函式,用以建立執行緒。start new thread函式成功建立後還可以對其進行操作。其函式原型 start new thread function,atgs kwargs 其引數含義如下 args 元組形式的引...

python 多執行緒程式設計

一 執行緒基礎 1 建立執行緒 thread模組提供了start new thread函式,用以建立執行緒。start new thread函式成功建立後還能夠對其進行操作。其函式原型 start new thread function,atgs kwargs 其引數含義例如以下 args 元組形式...

Python多執行緒程式設計

import threading import time deffunc name time.sleep 3 print 子執行緒 s 啟動 threading.current thread name print hello name print 子執行緒 s 結束 threading.curren...