我知道这个问题已被问过多次,但我找不到对我有帮助的答案。我的问题是我们可以在 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()
1 回答

宝慕林4294392
TA贡献2021条经验 获得超8个赞
这里的问题是你有targetasa()而不是a(注意括号)。这意味着,您正在调用该函数a,然后将其结果作为targetto 传递Thread。那不是你想要的——你想要的target是函数a本身。因此,在实例化Threads时只需删除括号,如下所示:
if __name__=="__main__":
t1=Thread(target=a)
t2=Thread(target=b)
t1.start()
t2.start()
添加回答
举报
0/150
提交
取消