Multithreading 线程启动时不调用它';s启动方法
我正要问另一个问题,这时我想到了这个问题。 请看一下这段代码:Multithreading 线程启动时不调用它';s启动方法,multithreading,python-3.x,Multithreading,Python 3.x,我正要问另一个问题,这时我想到了这个问题。 请看一下这段代码: import threading from http.server import HTTPServer, SimpleHTTPRequestHandler class Server(threading.Thread): def __init__(self, name, address='127.0.0.1',port=8080): threading.Thread.__init__(self, name=na
import threading
from http.server import HTTPServer, SimpleHTTPRequestHandler
class Server(threading.Thread):
def __init__(self, name, address='127.0.0.1',port=8080):
threading.Thread.__init__(self, name=name)
self.address = address
self.port=port
HandlerClass = SimpleHTTPRequestHandler
ServerClass = HTTPServer
self.httpd = ServerClass((address, port), HandlerClass)
def run(self):
self.httpd.serve_forever()
def shutdown(self):
self.httpd.shutdown()
self.httpd.socket.close()
httpd_thread= Server("http",'127.0.0.1',30820)
httpd_thread.start()
它创建一个http服务器,为脚本所在目录中的文件提供服务。它可以正常工作,但我不明白为什么它可以工作,因为我在启动线程时没有使用run()方法,
希望编写一些东西来调用run方法,但它只需启动线程即可工作。
我想知道原因。
谢谢。
注:我使用的是Python3.3。
问题是,如果调用
run
方法,您将在同一线程中运行该方法。start
方法首先创建一个新线程,然后在该线程中执行run
方法。这样,线程创建就从您身边抽象出来了
从开始的文档中
:
"""Start the thread's activity.
It must be called at most once per thread object. It arranges for the
object's run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the
same thread object.
"""
基本上你是说start()在初始化之后寻找run()方法。。。我已将run()重命名为asdsdre(),它不再自动启动。感谢您快速、完整、准确的回答。:)