Python线程 - 有什么区别?

use*_*094 0 python multithreading

谁能解释为什么这段代码什么都不打印:

import threading

def threadCode1(): 
    while True:
        pass      

def threadCode2():
    while True:
        pass


thread = threading.Thread(target=threadCode1())
thread2 = threading.Thread(target=threadCode2())
thread.start()
print('test')
thread2.start()
Run Code Online (Sandbox Code Playgroud)

但如果我删除括号:

thread = threading.Thread(target=threadCode1)
thread2 = threading.Thread(target=threadCode2)
Run Code Online (Sandbox Code Playgroud)

它打印'测试'?这对我来说是一个非常令人惊讶的结果.

Pau*_* Bu 5

因为,当您首次使用线程调用评估该行时:

thread = threading.Thread(target=threadCode1())
Run Code Online (Sandbox Code Playgroud)

该行的第一件事是执行threadCode1(),它使程序跳转到threadCode1函数体,这是一个无限循环,执行将永远不会使它脱离函数并执行主程序中的下一行.

如果你改成threadCode1这个:

def threadCode1(): 
    while True:
        print 'threadCode1'
Run Code Online (Sandbox Code Playgroud)

你会注意到它如何无休止地循环打印threadCode1.