Python Threading: Using the start() Method to Begin Thread Execution
Understand how to use Python's start()
method to initiate thread activity, invoking the run()
method in a separate thread. Learn about the RuntimeError
that occurs when start()
is called multiple times.
The start()
method begins the thread's activity. It must be called once a thread object is created. This method automatically invokes the object's run()
method in a separate thread. If called more than once, it raises a RuntimeError
.
Syntax
Here is the syntax to use the start()
method to start a thread:
Syntax
threading.Thread.start()
Example
Take a look at the following example:
Example
import threading
class MyThread(threading.Thread):
def run(self):
print("Thread is running")
# Create a new thread
thread1 = MyThread()
# Start the new thread
thread1.start()
Output
Thread is running
The run() Method
The run()
method represents the thread's activity and may be overridden in a subclass. The function passed to the constructor as the target argument is invoked by the object instead of the standard run()
method.