import threading def print_numbers(): i = 1 while True: print(i) i += 1 # Create and start a thread t = threading.Thread(target=print_numbers) t.start() # Wait for 5 seconds and then stop the thread t.join(5) if t.is_alive(): t._stop()
import threading import time class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True def run(self): while self.running: print("Thread is running...") time.sleep(1) def stop(self): self.running = False # Create and start a thread t = MyThread() t.start() # Wait for user input and then stop the thread input("Press Enter to stop the thread...") t.stop() t.join()In this example, we have defined a custom thread class that includes a stop() method. The run() method of the thread prints a message every second until the running flag is set to False. We have then used the stop() method to stop the thread in response to user input. The threading library is a built-in package in Python that provides classes and methods for creating and managing threads.