使用python进行多线程处理

时间:2015-11-30 19:19:00

标签: python multithreading python-multithreading python-multiprocessing

在python中使用多线程时,尝试理解以下结果。下面的代码以随机顺序将A和B打印到控制台,这是我想要实现的。但是第二段代码只打印了#34; 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

1 个答案:

答案 0 :(得分:0)

摆脱()testingNow.runA()中的testingNow.runB()

相关问题