当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Thread run()用法及代码示例


Python Thread.run() 方法

Thread.run() 方法是 Python 中线程模块的 Thread 类的内置方法。此方法用于表示线程的活动。它调用表示为 Thread 对象中的目标参数的方法以及分别取自 args 和 kwargs 参数的位置和关键字参数。这个方法也可以在子类中被覆盖。

模块:

    from threading import Thread

用法:

    run()

参数:

  • None

返回值:

这个方法的返回类型是<class 'NoneType'>,它什么都不返回。

例:

# Python program to explain the
# use of run() method in Thread class

import threading

def thread_1(i):
    print('Value by Thread 1:', i)

def thread_2(i):
    print('Value by Thread 2:', i)

def thread_3(i):
    print('Value by Thread 3:', i)    

    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))
thread3 = threading.Thread(target=thread_3, args=(3,))

# Running three thread object
thread1.run()
thread2.run()
thread3.run()

输出

Value by Thread 1:1
Value by Thread 2:2
Value by Thread 3:3

run()方法也可以在子类中被覆盖。下面给出创建 Thread 类的子类并覆盖 run 函数。

例:

# Python program to demonstrate 
# the overriding of run() method 

import threading 
  
class mythread(threading.Thread):
    def __init__(self, thread_name, thread_ID):
        threading.Thread.__init__(self) 
        self.thread_name = thread_name 
        self.thread_ID = thread_ID 
    
    # Overrriding of run() method in the subclass 
    def run(self):
        print("Thread name:"+str(self.thread_name) +"  "+ "Thread id:"+str(self.thread_ID)); 
  
thread1 = mythread("thread1", 1) 
thread2 = mythread("thread2", 2); 
  
thread1.start() 
thread2.start()

输出

Thread name:thread1  Thread id:1
Thread name:thread2  Thread id:2


相关用法


注:本文由纯净天空筛选整理自 Python Thread Class | run() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。