我是 Python 新手,所以如果这很明显,我深表歉意。
我正在尝试构建多线程应用程序,但是当我想创建一个线程时,我得到了两个而不是一个。
我的线程.py
from threading import Thread
import time
class MyThreadClass(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print "starting " + self.getName() + "\n"
from main import var1
while True:
print self.getName() + " is running\n"
print "value: " + var1 + "\n"
time.sleep(1)
主文件
from MyThread import MyThreadClass
var1 = "Test"
MyThreadClass().start()
我得到的输出
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
.....
为什么会这样?我注意到如果我替换MyThreadClass().start()
为MyThreadClass().run()
我得到 2 个线程但只有一个线程继续运行
Thread-1 is running
Thread-2 is running
Thread-2 is running
Thread-2 is running
Thread-2 is running
.....
知道代码有什么问题吗?