Python中的线程模块
与上一节中讨论的线程模块相比,Python2.4中包含的更新的线程模块为线程提供了更强大的高级支持。
线程模块公开了线程模块的所有方法,并提供了一些其他方法-
threading.activeCount()-返回活动的线程对象数。
threading.currentThread()-返回调用者的线程控件中线程对象的数量。
threading.enumerate()-返回当前处于活动状态的所有线程对象的列表。
除了这些方法之外,线程模块还具有实现线程的Thread类。Thread类提供的方法如下-
run() -run()方法是线程的入口点。
start() -该start()方法通过调用run方法来启动线程。
join([time]) -join()等待线程终止。
isAlive() -该isAlive()方法检查线程是否仍在执行。
getName() -该getName()方法返回线程的名称。
setName() -该setName()方法设置线程的名称。
使用线程模块创建线程
要使用线程模块实现新线程,您必须执行以下操作-
定义Thread类的新子类。
重写__init__(self[,args])方法以添加其他参数。
然后,重写run(self[,args])方法以实现线程在启动时应执行的操作。
一旦创建了新的Thread子类,就可以创建它的实例,然后通过调用start()来启动新线程,该start()依次调用run()方法。
示例
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"执行以上代码后,将产生以下结果-
Starting Thread-1 Starting Thread-2 Exiting Main Thread Thread-1: Thu Mar 21 09:10:03 2013 Thread-1: Thu Mar 21 09:10:04 2013 Thread-2: Thu Mar 21 09:10:04 2013 Thread-1: Thu Mar 21 09:10:05 2013 Thread-1: Thu Mar 21 09:10:06 2013 Thread-2: Thu Mar 21 09:10:06 2013 Thread-1: Thu Mar 21 09:10:07 2013 Exiting Thread-1 Thread-2: Thu Mar 21 09:10:08 2013 Thread-2: Thu Mar 21 09:10:10 2013 Thread-2: Thu Mar 21 09:10:12 2013 Exiting Thread-2