Python threads with params

the living tribunal

Moderator
Staff member
moderator
Python:
import threading

# Define a function for the thread
def print_numbers(thread_name, count):
    for i in range(count):
        print(f"{thread_name}: {i}")

# Create two threads
thread1 = threading.Thread(target=print_numbers, args=("Thread-1", 5))
thread2 = threading.Thread(target=print_numbers, args=("Thread-2", 5))

# Start the threads
thread1.start()
thread2.start()

# Wait for both threads to complete
thread1.join()
thread2.join()

print("Both threads have finished execution.")
 

the living tribunal

Moderator
Staff member
moderator
Python:
import threading

class MyClass:
    def __init__(self, name):
        self.name = name

    def print_numbers(self, count):
        for i in range(count):
            print(f"{self.name}: {i}")

    def start_threads(self):
        # Create threads
        thread1 = threading.Thread(target=self.print_numbers, args=(5,))
        thread2 = threading.Thread(target=self.print_numbers, args=(5,))

        # Start threads
        thread1.start()
        thread2.start()

        # Wait for both threads to complete
        thread1.join()
        thread2.join()

        print("Both threads have finished execution.")

# Create an instance of MyClass
obj = MyClass("Thread")

# Start threads from within the class
obj.start_threads()
 
Top