我喜欢用代码来理解程序,而不是单单的教程
类 ThreadClass 继承自 threading.Thread,也正因为如此,您需要定义一个 run 方法,以此执行您在该线程中要运行的代码。在这个 run 方法中唯一要注意的是,self.getName()是一个用于确定该线程名称的方法。
#! /usr/bin/env python
#coding=utf-8
import threading
import datetime
import time
import random
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
print "%s says Hello World at time: %s" % (self.getName(),now)
x = random.randint(1,5)
print x
time.sleep(x)
print 'End %s' % (self.getName())
for i in range(5):
t = ThreadClass()
t.start()
输出
Thread-1 says Hello World at time: 2014-07-11 16:22:56.820320Thread-2 says Hello World at time: 2014-07-11 16:22:56.820502
5
Thread-3 says Hello World at time: 2014-07-11 16:22:56.820777
4
4
Thread-4 says Hello World at time: 2014-07-11 16:22:56.820988
5
Thread-5 says Hello World at time: 2014-07-11 16:22:56.821276
4
End Thread-1
End Thread-3
End Thread-5
End Thread-2
End Thread-4
我们可以发现5个多线程的子线程是在并行运作的,而不是顺序运作。
要点:
1.定义一个多线程的类
class ThreadClass(threading.Thread):
2.必须带有函数run
def run(self):