首页 > 编程 > Python > 正文

Python threading多线程编程实例

2020-02-23 05:49:34
字体:
来源:转载
供稿:网友

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
    #调用父类构造函数
 
  def run(self):
    #重写run()函数,线程默认从此函数开始执行
    print "This is " + self.t_name
 
if __name__ == '__main__':
  thread1 = Th("Thread_1")
  thread1.start()
  #start()函数启动线程,自动执行run()函数

threading.Thread 类的可继承函数:
getName() 获得线程对象名称
setName() 设置线程对象名称
join() 等待调用的线程结束后再运行之后的命令
setDaemon(bool) 阻塞模式, True: 父线程不等待子线程结束, False 等待,默认为 False
isDaemon() 判断子线程是否和父线程一起结束,即 setDaemon() 设置的值
isAlive() 判断线程是否在运行

实例

代码如下:
import threading
import time
class Th(threading.Thread):
  def __init__(self, thread_name):
    threading.Thread.__init__(self)
    self.setName(thread_name)
 
  def run(self):
    print "This is thread " + self.getName()
    for i in range(5):
      time.sleep(1)
      print str(i)
    print self.getName() + "is over"

join() 阻塞等待

代码如下:
if __name__ == '__main__':
    thread1 = Th("T1 ")
    thread1.start()
    #thread1.join()
    print "main thread is over"

不带 thread1.join() ,得到如下结果:
代码如下:
This is thread T1
main thread is over
0
1
2
T1 is over

不等待 thread1 完成,执行之后语句。
加了 thread1.join() ,得到如下结果:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表