python 多线程 线程池

本文探讨了在使用ThreadPool和自定义线程类进行多线程测试时遇到的问题,提供了问题排查和优化并行执行的解决方案,适合深入理解并发编程的读者。

测试多线程的时候 出现了这种情况 怎么解

import threadpool
import time

def sayHello(name):
    print("hello", name)
    time.sleep(2)

start_time = time.time()
pool = threadpool.ThreadPool(10)
requests=threadpool.makeRequests(sayHello, [a for a in 'AHHHHHHHHHHHHHHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'])
[pool.putRequest(req) for req in requests]
pool.wait()
print ('%d second'% (time.time()-start_time))

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()
        self.n = n


    def run(self):
        print('task', self.n)
        time.sleep(1)
        print('task '+self.n + ' remains 2s')
        time.sleep(1)
        print('task ' + self.n + ' remains 1s')
        time.sleep(1)
        print('task ' + self.n + ' remains 0s')

if __name__=='__main__':

    for i in range(10):
        t = MyThread('t'+str(i))
        t.start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值