这篇文章主要介绍了Python
threading多线程编程实例,本文讲解了使用函数和线程类实现多线程编程的例子,需要的朋友可以参考下
Python 的多线程有两种实现方法:
函数,线程类
1.函数
调用 thread 模块中的 start_new_thread()
函数来创建线程,以线程函数的形式告诉线程该做什么
代码如下:
# -*- coding: utf-8 -*-
import thread
def f(name):
#定义线程函数
print "this is " name
if __name__ == '__main__':
thread.start_new_thread(f, ("thread1",))
#用start_new_thread()调用线程函数和其他参数
while 1:
pass
不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用 while 1
这种方法解决。
2.线程类
调用 threading 模块,创建 threading.Thread
的子类来得到自定义线程类。
代码如下:
# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name
= name
#调