python 多线程怎么使用
Python中实现多线程有两种方式:使用threading模块和使用concurrent.futures模块。
使用threading模块:
-
导入threading模块。
-
定义一个函数作为线程执行的目标函数。
-
创建线程对象,调用start()方法启动线程。
示例代码:
import threading
def target_function():
print("Hello, World!")
thread = threading.Thread(target=target_function)
thread.start()
使用concurrent.futures模块:
-
导入concurrent.futures模块。
-
定义一个函数作为线程执行的目标函数。
-
创建ThreadPoolExecutor对象,调用submit()方法提交任务。
-
调用result()方法获取任务执行结果。
示例代码:
from concurrent.futures import ThreadPoolExecutor
def target_function():
return "Hello, World!"
executor = ThreadPoolExecutor(max_workers=1)
future = executor.submit(target_function)
result = future.result()
print(result)
需要注意的是,Python中的多线程并不是真正意义上的并行执行,而是通过轮流执行线程来实现伪并行。在CPU密集型的任务上,多线程的效果并不明显,而在I/O密集型的任务上,多线程能够显著提高程序的性能
原文地址: https://www.cveoy.top/t/topic/gZa0 著作权归作者所有。请勿转载和采集!