使用python的多线程

2024-03-29 09:40:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中使用多线程时,尝试理解以下结果。下面的代码以随机顺序将A和B打印到控制台,这就是我想要实现的。但是第二段代码只将“A”打印到控制台,并且永远不会超过t1.start()。为什么会这样?我需要对代码的第二部分做些什么才能使它像第一部分一样工作?你知道吗

提前谢谢,这是我的第一篇帖子。你知道吗

这就是我想要的行为:

from threading import Thread
def runA():
    while True:
        print ('A\n')

def runB():
    while True:
        print ('B\n')

if __name__ == "__main__":
     t1 = Thread(target = runA())
     t2 = Thread(target = runB())
     t1.setDaemon(True)
     t2.setDaemon(True)
     t1.start()
     t2.start()
     while True:
         pass

我希望从上面的代码生成行为,但是使用下面的示例中的类。下面的代码从不执行t2.start()。为什么会这样?你知道吗

from threading import Thread
class test():
     def runA(self):
         while True:
             print ('A\n')

     def runB(self):
         while True:
             print ('B\n')

if __name__ == "__main__":
     testingNow=test()
     t1 = Thread(target = testingNow.runA())
     t2 = Thread(target = testingNow.runB())
     t1.setDaemon(True)
     t2.setDaemon(True)
     t1.start()
     t2.start()
     while True:
         pass

Tags: 代码fromtruetargetdefthreadstartt1