Python中为类成员函数启动线程的实现方式

一颗松果
一颗松果
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍在Python中如何为类的成员函数开启独立线程。通过实例化threading.Thread并指定目标函数及参数,实现异步执行。代码展示了如何传递self对象至线程函数,并演示了start与join的使用,确保线程执行完毕后再继续主流程。

具体实现代码如下所示:

# -*- coding: utf-8 -*-
import threading
import thread
import time


class Test(object):
  def __init__(self):
    # threading.Thread.__init__(self)
    self._sName = "machao"

  def process(self):
    #args是关键字参数,需要加上名字,写成args=(self,)
    th1 = threading.Thread(target=Test.buildList, args=(self,))
    th1.start()
    th1.join()

  def buildList(self):
    while True:
      print "start"
      time.sleep(3)


test = Test()
test.process()

以上关于Python中为类的成员函数开启线程的方法即为本文分享的全部内容,希望能为读者提供有价值的参考。如果您觉得有用,欢迎继续支持本站获取更多技术资讯。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表