下面是一个python代码片段。你知道吗
import threading
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
currentTreadname = threading.currentThread()
print "running in", currentTreadname
让我们来看看实例类
thread = myThread(1,"mythrd",1)
并在其中调用run方法。你知道吗
thread.run()
running in <_MainThread(MainThread, started 139982993762048)>
主线程在这里意味着什么线程.运行() ? 在螺纹手册中:
The standard run() method invokes the callable object passed to the object’s constructor as the target argument.
1.这里有两个对象,例如我的示例,第一个可调用对象意味着_MainThread
?to the object’s constructor
中的第二个对象表示myThread的构造函数,对吗?
2.为什么子类中的run方法可以调用父类?你知道吗
thread.run()
running in <_MainThread(MainThread, started 139982993762048)>
线程是子类的实例——myThread(1,“mythrd”,1),为什么线程.运行()是否撤消主线程?你知道吗
你应该打电话给警察线程.开始()方法。你知道吗
输出为:
正如文档所说,start()方法启动线程的活动,是的,这个活动是run()方法。
更新
标准run()方法调用作为目标参数传递给对象构造函数的可调用对象。
第二个对象是您的myThread实例,您是对的。但可调用的对象不是你说的。看看这个穿线。穿线定义:
可调用对象是您传递给它的目标参数。关于这一点,您可以参考https://docs.python.org/2/library/threading.html
为什么要打印代码
running in <_MainThread(MainThread, started 139982993762048)>
?因为您不调用
Thread.start
方法,所以它不会启动新线程。因此,如果您只调用myThread.run
,它只是一个普通的对象方法调用。它在主线程中调用。所以它会打印这个。你知道吗我认为你应该遵循上面的GuangshengZuo答案如果你想正确使用线程,我试着提供你想要的答案:
_MainThread是线程模块中的一个类。您可以很容易地检查变量currentTreadname的类型,正如我所做的,如下所示:
输出:
相关问题 更多 >
编程相关推荐