一、开启线程的两种方式

开启线程的两种方式

Python中使用线程有两种方式:函数或者用类来包装线程对象

一、函数方式

函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:

_thread.start_new_thread ( function, args[, kwargs] )
'''
参数说明:
1. function - 线程函数。
2. args - 传递给线程函数的参数,他必须是个tuple类型。
3. kwargs - 可选参数。
'''

二、使用threading模块

multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,因而不再详细介绍

三、继承Thread类

我们可以通过直接从threading.Thread类继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即使用start()方法会首先调用线程的 run() 方法:

from threading import Thread
import time


class Sayhi(Thread):
    def __init__(self,name):
        # 获取Thread类中__init__方法的所有代码
        super().__init__()
        # 在基础上增加name属性
        self.name=name
    def run(self):
        '''
        如果继承Thread类,必须重写run方法,run方法内就是子线程需要执行的代码
        '''
        time.sleep(2)
        print('%s say hello' % self.name)


'''
尽管线程无需像进程一样,需要写入到if __name__ == '__main__':语句中
但是为了养成良好的编码习惯,我们还是将启动代码写入到该语句中
'''
if __name__ == '__main__':
    t = Sayhi('egon')
    t.start()
    print('主线程')
posted @ 2021-06-03 18:27  zzwYYYYYY  阅读(560)  评论(0)    收藏  举报