我们知道单核cpu同时只能执行一个任务。如果在一个单核cpu的电脑上,我们可以同时登入qq、听音乐或者写文档等,给我们的感觉它们就是同时在进行的。这是由于cpu的分时技术,使它不断的进行上下文的切换,根据任务的优先级不停的在各个任务间切换执行。而且由于cpu运行太快,我们根本感觉不到它在切换任务,所以就给了我们同时在执行多个任务。
2.1 创建线程
import threading # 线程模块
# 定义每个线程要运行的函数
def run(n):
print(‘task‘, n)
if __name__ == ‘__main__‘:
# 生成一个线程实例 , 参数为 元组形式
t1 = threading.Thread(target=run, args=("t1",))
# 生成另一个线程实例 , 参数为 元组形式
t2 = threading.Thread(target=run, args=("t2",))
# 启动线程
t1.start()
t2.start()
2.2 对比运行
好像运行结果除了同时出来外,没什么特别的,我们稍稍修改一下
import threading
import time
def run(n):
print(‘task‘, n)
time.sleep(2)
if __name__ == ‘__main__‘:
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
# t1.start()
# t2.start()
run(‘t1‘)
run(‘t2‘)
我们让程序sleep一会,就能很明显看出并发运行的效果了
上面使用线程方法可以被称为直接调用,而继承式调用需要我们自己写一个类,继承threading.Thread
方法:
import threading
import time
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print(‘task‘, self.n)
time.sleep(2)
if __name__ == ‘__main__‘:
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
原文:http://www.cnblogs.com/bigberg/p/7810955.html