python線程任務run
Python Thread.run()方法 (Python Thread.run() Method)
Thread.run() method is an inbuilt method of the Thread class of the threading module in Python. This method is used to represent a thread's activity. It calls the method expressed as the target argument in the Thread object along with the positional and keyword arguments taken from the args and kwargs arguments, respectively. This method can also be overridden in the subclass.
Thread.run()方法是Python中線程模塊的Thread類的內置方法。 此方法用于表示線程的活動。 它調用在Thread對象中表示為目標參數的方法,以及分別從args和kwargs參數獲取的position和關鍵字參數。 也可以在子類中重寫此方法。
Module:
模塊:
from threading import Thread
Syntax:
句法:
run()
Parameter(s):
參數:
None
沒有
Return value:
返回值:
The return type of this method is <class 'NoneType'>, it returns nothing.
此方法的返回類型為<class'NoneType'> ,它什么也不返回。
Example:
例:
# 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()
Output
輸出量
Value by Thread 1: 1
Value by Thread 2: 2
Value by Thread 3: 3
run() method can also be overridden in the subclass. Given below creates a subclass of the Thread class and overrides the run function.
run()方法也可以在子類中重寫。 下面給出的創建Thread類的子類并覆蓋run函數。
Example:
例:
# 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()
Output
輸出量
Thread name: thread1 Thread id: 1
Thread name: thread2 Thread id: 2
翻譯自: https://www.includehelp.com/python/thread-run-method-with-example.aspx
python線程任務run