我很黑! 发表于 2018-8-15 11:26:04

python多线程之自定义线程类

'''自定义线程类'''  
from threading import Thread
  
import time
  

  
#创建一个类,并继承Python的Thread类,且重写run()方法实现具体的执行顺序由自己来定义
  
class MyThread(Thread):
  
    '''time.sleep代表等待10秒后才执行'''
  
    def run(self):
  
      time.sleep(2)
  
      print("我是线程类...")
  

  
      '''下面这一段是从源码Thread类中的run方法复制过来的,当然
  
      没有也许,因为继承了Thread,就会去父类里面找,我这里只是测试用'''
  
      try:
  
            if self._target:
  
                self._target(*self._args, **self._kwargs)
  
      finally:
  
            # Avoid a refcycle if the thread is running a function with
  
            # an argument that has a member that points to the thread.
  
            del self._target, self._args, self._kwargs
  

  
#定义一个函数
  
def Bar():
  
    print("Bar...")
  

  
#通过自定义的线程类来创建线程,并且关联函数Bar,最后执行这个线程
  
t1 = MyThread(target=Bar)
  
t1.start()
  

  
print("守护线程执行结束...")
页: [1]
查看完整版本: python多线程之自定义线程类