
线程就是一个可以被系统计划调度执行的程序序列的最小单元程序,是操作系统非常典型的一部分。计算机程序里的线程,是一个可以执行的路径。线程可以在程序里面创建独立的执行路径。每个程序至少开始于一个执行路径。按照需要可以创建更多的线程并行执行,有效利用资源。多线程应用程序有两个优势:
- 提升应用程序的识别响应度
- 在多核系统中提升应用程序的实时性能
标准库实现了线程设计,线程程序设计需要注意资源控制的同时性竞争问题。
创建线程
threading 模块里面的 Thread 模块提供了简单的功能性和高级别的操作接口,导入库的方法:
from threading import Thread
线程实例
下面的例子演示了 python 如何使用线程调用函数, 最简单的方法是调用start_new_thread() 方法。
def yourFunc():
print "函数被调用!!"
thread.start_new_thread(yourFunc, ())
thread.start_new_thread 方法启动一个新的线程,返回一个标识id。这个函数执行完毕,线程即退出。
例子
import time
from threading import Thread
def myfunc(i):
print ("挂起前 :", i)
time.sleep(5)
print ("挂起后 :", i)
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
输出

创建一个线程类
Python 在 Thread 模块之上提供了 threading 模块,典型的使用方法是申请 Thread 类的子类,并重载 run() 方法,实现所需要的功能。
class MyThreadClass(threading.Thread):
def run(self):
在这里,MyThreadClass 是 Thread 类的子类。接下来需要定义这个类的 run 方法。 MyThreadClass 类的 run() 方法是线程的入口。在调用 MyThreadClass 类对象的 start() 方法时,run() 方法将被执行。 可以将函数或者其他可调用的对象传给类的构造器。
t = MyThreadClass()
t.start()
程序代码
import threading
import datetime
class MyThreadClass(threading.Thread):
def run(self):
dt = datetime.datetime.now()
print (self.getName(), "当前的日期时间 : ", dt)
for i in range(5):
t = MyThreadClass()
t.start()
输出
Thread-1 当前的日期时间 : 2015-10-04 17:09:48.423745
Thread-2 当前的日期时间 : 2015-10-04 17:09:48.423745
Thread-3 当前的日期时间 : 2015-10-04 17:09:48.423745
Thread-4 当前的日期时间 : 2015-10-04 17:09:48.423745
Thread-5 当前的日期时间 : 2015-10-04 17:09:48.423745
上面的代码,MyThreadClass 继承自 threading.Thread ,重载 run() 方法。其中的 self.getName() 可以获得线程的标识名称,t.start() 启动这些线程。
【编程】Python 读写CSV文件
【编程】Python 解析XML
【编程】Python 终止程序
【编程】Python 随机数
【编程】Python 异常处理
【编程】Python 日期和时间
【编程】Python 多线程套接字
【编程】Python 套接字
【编程】Python FTP
【编程】Python 网页