_thread.exit() 使用demo
时间: 2023-08-16 09:07:33 浏览: 42
_thread.exit() 是用于退出当前线程的方法。在使用时,需要导入 _thread 模块。
下面是一个使用 _thread.exit() 的简单示例:
```python
import _thread
import time
def my_thread(name, delay):
print("Thread {} started".format(name))
time.sleep(delay)
print("Thread {} exiting".format(name))
_thread.exit()
_thread.start_new_thread(my_thread, ("Thread 1", 5))
_thread.start_new_thread(my_thread, ("Thread 2", 2))
```
在上面的示例中,我们定义了一个名为 my_thread 的函数,它的参数包括线程名称和延迟时间。函数执行时,会先打印出线程开始的信息,然后等待指定的延迟时间后,打印出线程结束的信息,并调用 _thread.exit() 方法退出线程。
在主程序中,我们使用 _thread.start_new_thread() 方法启动两个线程,分别是 my_thread("Thread 1", 5) 和 my_thread("Thread 2", 2)。这两个线程会分别等待 5 秒和 2 秒后执行退出操作。
需要注意的是,_thread.exit() 方法会立即终止当前线程的执行,因此在使用时需要谨慎。如果有资源需要清理,可以在退出前进行清理操作。