python线程池示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python线程池示例相关的知识,希望对你有一定的参考价值。

 

使用with方式创建线程池,任务执行完毕之后,会自动关闭资源 , 否则就需要手动关闭线程池资源 

 

import threading, time
from concurrent.futures import ThreadPoolExecutor, as_completed


class MyTask(threading.Thread):
    """
        使用python线程的方法
    """

    def __init__(self, thread_id):
        threading.Thread.__init__(self)
        self.thread_id = thread_id

    def run(self):
        while 1:
            print(%s线程正在运行。。。。。。。。 % self.thread_id)
            time.sleep(1)


class MyThreadPool(object):
    """
        使用python线程池的两种方式
    """


    def __init__(self):
        """init方法,构造测试数据"""
        self.param_data = []
        for i in range(1000):
            self.param_data.append(str(i))


    def target_task(self, param):
        """目标方法"""
        print(threading.currentThread().name)  # 打印当前线程的name
        # print(param)
        return param + ----------task

    def execute_thread_pool_method1(self):
        """使用线程池的第一种方式"""
        ‘‘‘创建一个线程池,里面有10个线程‘‘‘
        with ThreadPoolExecutor(max_workers=10, thread_name_prefix=test) as tpe:  # 使用with,会自动关闭任务
            result = []  # 缓存线程任务执行结果

            for i in self.param_data:
                r = tpe.submit(self.target_task, i)  # submit提交任务,执行的顺序是乱的
                result.append(r)

            for r in as_completed(result):
                print(r.result())

            tpe.shutdown()

    def execute_thread_pool_method2(self):
        """使用线程池的第二种方式"""
        ‘‘‘创建一个线程池,里面有10个线程‘‘‘
        with ThreadPoolExecutor(10) as tpe:
            #  结果的数据类型就是list
            result = tpe.map(self.target_task, self.param_data)
            for r in result:  # 对结果集进行处理
                print(r)


if __name__ == __main__:
    my_task = MyTask(1)

    my_task.setDaemon(True)  # 将my_task这个线程设置成守护线程
    my_task.start()
    print(threading.active_count())   # 打印活着的线程数


    # my_thread_pool = MyThreadPool()
    # my_thread_pool.execute_thread_pool_method1()
    # my_thread_pool.execute_thread_pool_method2()

 

 

以上是关于python线程池示例的主要内容,如果未能解决你的问题,请参考以下文章

python线程池示例

线程池与并行度

Java——线程池

Motan在服务provider端用于处理request的线程池

pythonThreadpool线程池任务终止简单示例

Java线程池详解