Python 多线程

来源:互联网 发布:医院数据质量分析报告 编辑:程序博客网 时间:2024/06/14 10:31

一、介绍

线程是操作系统能够进行运算调度的最小单位。

Python的标准库提供了两个模块:threadthreadingthread是低级模块,threading是高级模块,对thread进行了封装,只需要使用threading这个高级模块。

import time, threading# 新线程执行的代码:def loop():    print 'thread %s is running...' % threading.current_thread().name    n = 0    while n < 5:        n = n + 1        print 'thread %s >>> %s' % (threading.current_thread().name, n)        time.sleep(1)    print 'thread %s ended.' % threading.current_thread().nameprint 'thread %s is running...' % threading.current_thread().namet = threading.Thread(target=loop, name='LoopThread')t.start()t.join()print 'thread %s ended.' % threading.current_thread().name

启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行。

由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程,Python的threading模块有个current_thread()函数,它永远返回当前线程的实例。主线程实例的名字叫MainThread,子线程的名字在创建时指定,我们用LoopThread命名子线程。名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1Thread-2……

二、使用线程

1、线程的创建

import threadingimport timedef run(n):    print("task", n)    time.sleep(1)    print('2s')    time.sleep(1)    print('1s')    time.sleep(1)    print('0s')    time.sleep(1)if __name__ == "__main__":    t1 = threading.Thread(target=run, args=("t1",))    t2 = threading.Thread(target=run, args=("t2",))    t1.start()    t2.start()

2、继承threading.Thread来自定义线程类,其本质是重构Thread类中的run方法

import threadingimport timeclass MyThread(threading.Thread):    def __init__(self, n):        super(MyThread, self).__init__()  # 重构run函数必须要写        self.n = n    def run(self):        print("task", self.n)        time.sleep(1)        print('2s')        time.sleep(1)        print('1s')        time.sleep(1)        print('0s')        time.sleep(1)if __name__ == "__main__":    t1 = MyThread("t1")    t2 = MyThread("t2")    t1.start()    t2.start()
点击打开链接















原创粉丝点击