Python的Lib里,提供了两种使用Threading的方法:
一、函数式:
import time
import thread

def timer(no, interval):
while True:
print 'Thread: (%d) Time: %s' % (no, time.ctime())
time.sleep(interval)

def test():
thread.start_new_thread(timer, (1, 1))
thread.start_new_thread(timer, (2, 3))

if __name__ == '__main__':
test()
thread.start_new_thread(function, args[, kwargs])
import threading
import time

class timer(threading.Thread):
def __init__(self, no, interval):
threading.Thread.__init__(self)
self.no = no
self.interval = interval

def run(self):
"重写 run() 方法,实现自己的线程函数"
while True:
print 'Thread Object (%d), Time: %s' % (self.no, time.ctime())
time.sleep(self.interval)

def test():
threadone = timer(1, 1)
threadtwo = timer(2, 3)

threadone.start()
threadtwo.start()

if __name__ == '__main__':
test()
一、函数式:
















这个是函数原型, 其中, function是要调用的线程函数;args是传递给你的线程函数的参数,必须是Tuple类型;kwargs是可选参数。
这种线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用 thread.exit(), 抛出SystemExit exception, 达到退出线程的目的。
二、继承自 threading.Thread类
























其中, thread和threading的模块中还包含很多关于多线程编程的东西,如锁、定时器、获得激活线程列表等等。