我知道這個問題已被問過多次,但我找不到對我有幫助的答案。我的問題是我們可以在 python 中并行執行兩個函數,其中每個函數都有一個 for 循環運行并打印一些值。例如,我有兩個函數 a() 和 b(),其中 a() 打印數字 1..n(比如 n=3),b() 打印數字 11..n(比如 n=13)連同當前時間。我希望輸出是這樣的:function a :1 2018-11-02 15:32:58function b :11 2018-11-02 15:32:58function a :2 2018-11-02 15:32:59function b :12 2018-11-02 15:32:59但它目前打印以下內容:function a :1 2018-11-02 15:32:58function a :2 2018-11-02 15:32:59function b :11 2018-11-02 15:33:00function b :12 2018-11-02 15:33:01代碼:import timefrom threading import Threadimport datetimedef a(): for i in range(1,3): print 'function a :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) time.sleep(1)def b(): for i in range(11,13): print 'function b :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) time.sleep(1)if __name__=="__main__": t1=Thread(target=a()) t2=Thread(target=b()) t1.start() t2.start()
在python中并行執行'N'個函數
慕的地6264312
2021-08-05 17:50:23
