我知道这个问题已被问过多次,但我找不到对我有帮助的答案。我的问题是我们可以在 python 中并行执行两个函数,其中每个函数都有一个 for 循环运行并打印一些值。例如,我有两个函数 a() 和 b(),其中 a() 打印数字 1..n(比如 n=3),b() 打印数字 11..n(比如 n=13)连同当前时间。我希望输出是这样的:
function a :1 2018-11-02 15:32:58
function b :11 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :12 2018-11-02 15:32:59
但它目前打印以下内容:
function a :1 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :11 2018-11-02 15:33:00
function b :12 2018-11-02 15:33:01
代码:
import time
from threading import Thread
import datetime
def 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()
宝慕林4294392
相关分类