在Python中启动一个线程可以通过以下几种方法:
1. 使用`threading`模块:
import threading
def target_function():
线程要执行的任务
pass
创建线程对象
t = threading.Thread(target=target_function)
启动线程
t.start()
等待线程结束(可选)
t.join()
2. 继承`threading.Thread`类并重写`run`方法:
import threading
class MyThread(threading.Thread):
def run(self):
线程要执行的任务
pass
创建线程对象
t = MyThread()
启动线程
t.start()
等待线程结束(可选)
t.join()
3. 使用`concurrent.futures`模块的`ThreadPoolExecutor`:
import concurrent.futures
def target_function():
线程要执行的任务
pass
创建线程池
with concurrent.futures.ThreadPoolExecutor() as executor:
提交任务到线程池
future = executor.submit(target_function)
4. 使用较低级的`_thread`模块(不推荐,主要用于低级操作):
import _thread
def target_function():
线程要执行的任务
pass
启动线程
_thread.start_new_thread(target_function, ())