1. 程式人生 > >Python之多執行緒:python多執行緒設計之同時執行多個函式命令詳細攻略

Python之多執行緒:python多執行緒設計之同時執行多個函式命令詳細攻略

Python之多執行緒:python多執行緒設計之同時執行多個函式命令詳細攻略

目的

同時執行多個函式命令

 

採取方法

T1、單個實現

import threading
 
threading.Thread(target=my_record()).start()
threading.Thread(target= voice_tts()).start()


import threading

processing2=threading.Thread(target= voice_tts())
processing1=threading.Thread(target=my_record())

processing1.start()
processing2.start()
processing1.join()
processing2.join()

T2、列表for迴圈實現

#實現多執行緒
threads = []
t1 = threading.Thread(target=my_record())
threads.append(t1)
t2 = threading.Thread(target=voice_tts())
threads.append(t2)
 
for t in threads:
    t.setDaemon(True)
    t.start()
t.join()
print("ok") 

 

應用場景

1、多個按鈕函式內呼叫一個主類,繼承threading.Thread

import threading
class MyThread01(threading.Thread):
    def __init__(self,parent=None):
        threading.Thread.__init__(self)

    def run(self):
        print('執行緒開啟!')


#按鈕101
    def test_run():
        time.sleep(2)
    testthread = MyThread01(test_run)
    testthread.start()
    voice_tts()

#按鈕102
    def test_run():
        time.sleep(2)
    testthread = MyThread01(test_run)
    testthread.start()
    my_record()