【python日记】多线程

import datetime, time
import threading

prtnoList = [3, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44, 2, 3, 4, 5, 6, 78, 9, 0, 123, 15, 23, 44]

def print_time(name):
    print('1', datetime.datetime.now())
    time.sleep(2)
    print(name, datetime.datetime.now())

# 方式1:直接用函数实现
#try:
#    threads = []
#    for name in prtnoList:
#        threads.append(threading.Thread(target=print_time, args=(name,)))
#    for i in range(0, len(prtnoList), 10):
#        sub_threads = threads[i:i+10]
#        for thread in sub_threads:
#            thread.start()
#            if sub_threads.index(thread) == 9:
#                thread.join()



# 方式2:重写类
class myThead(threading.Thread):
    def __init__(self, theadID, name):
        threading.Thread.__init__(self)
        self.theadID = theadID
        self.name = name

    def run(self):
        print_time(self.name)

# 线程池
theads = []
for i in prtnoList:
    theads.append(myThead(str(i)+'1', str(i)))

# 将线程池中的线程分组执行
for i in range(0, len(theads), 10):
    sub_theads = theads[i:i+10]
    for thead in sub_theads:
        thead.start()
        # 等待上一组线程(10个)执行完再执行下一组
        if sub_theads.index(thead) == 9:
            thead.join()

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值