當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。