python – 线程的启动的几种方式

本文主要给大家介绍python启动线程的四种方式

1. 使用 threading 模块

创建 Thread 对象,然后调用 start() 方法启动线程。

import threading

def func():
    print("Hello, World!")

t = threading.Thread(target=func)
t.start()

2. 继承 threading.Thread 类

重写 run() 方法,并调用 start() 方法启动线程。

import threading

class MyThread(threading.Thread):
    def run(self):
        print("Hello, World!")

t = MyThread()
t.start()

3. 使用 concurrent.futures 模块

使用ThreadPoolExecutor 类的 submit() 方法提交任务,自动创建线程池并执行任务。

import concurrent.futures

def func():
    print("Hello, World!")

with concurrent.futures.ThreadPoolExecutor() as executor:
    future = executor.submit(func)

4. 使用 multiprocessing 模块的 Process 类

创建进程,然后在进程中启动线程。

import multiprocessing
import threading

def func():
    print("Hello, World!")

if __name__ == "__main__":
    p = multiprocessing.Process(target=func)
    p.start()
    p.join()

以上就是python中启动线程的几种方式的介绍,希望对你有所帮助。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年11月6日
下一篇 2023年11月6日

相关推荐