python-Thread子类创建进程 作者:马育民 • 2019-02-21 13:33 • 阅读:10117 # 概述 当子线程需要实现 **复杂功能** 时,像之前那样,只一个函数是很难实现的,就需要通过类来实现。 ### 使用方法 定义新类,继承Thread类,重写run()方法,实例化后调用start()方法启动线程。 子线程就会执行run()方法。 ### 例子1 ``` #coding=utf-8 from threading import Thread class MyThread(Thread): def run(self): print('name=%s'%self.name) if __name__ == "__main__": #创建线程 mt=MyThread() #启动线程 mt.start() ``` ### 例子2 给线程传值 ``` #coding=utf-8 from threading import Thread,current_thread class MyThread(Thread): def __init__(self,name,num): self.name=name self._num=num def run(self): print('name=%s,num=%d'%(current_thread().name,self._num)) if __name__ == "__main__": #创建线程 mt=MyThread('子线程',10) #启动线程 mt.start() ``` 执行报错: ``` Traceback (most recent call last): File "c:/Users/mym/Desktop/python/练习/12.py", line 16, in mt=MyThread('子线程',10) File "c:/Users/mym/Desktop/python/练习/12.py", line 8, in __init__ self.name=name File "C:\devtools\Anaconda3\lib\threading.py", line 1089, in name assert self._initialized, "Thread.__init__() not called" AssertionError: Thread.__init__() not called ``` 修改代码如下: ``` #coding=utf-8 from threading import Thread,current_thread class MyThread(Thread): def __init__(self,name,num): Thread.__init__(self) self.name=name self._num=num def run(self): print('name=%s,num=%d'%(current_thread().name,self._num)) if __name__ == "__main__": #创建线程 mt=MyThread('子线程',10) #启动线程 mt.start() ``` 原文出处:http://malaoshi.top/show_1EF2pyB7ORJE.html