控制多线程的数量

1、通过threading.BoundedSemaphore,这种方法是分批灌线程,分批执行,等所有线程灌完了才会执行最后的print

# -*- coding:utf-8 -*-
import threading
import time


class Test(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def printthread(self):
        print self.name, "-->进程创建"
        time.sleep(2)
        print self.name, "-->进程结束"
        threadmax.release()

    def run(self):
        self.printthread()  #要执行的函数

if __name__ =='__main__':
    threadmax = threading.BoundedSemaphore(3)  # 限制1次装载3个线程
    threads=[]
    for a in range(5):
        threadmax.acquire()
        a=Test()
        threads.append(a)
        a.start()
    print("=============")  # 需要等到线程全部装载完了才会打印这一行

2、使用threading.Semaphore(),这种感觉是一次性灌所有线程,但是分批执行,不阻塞下面的代码

# -*- coding:utf-8 -*-
import threading,Queue
from time import sleep


class Test(threading.Thread):
    def __init__(self, lock, num):
        threading.Thread.__init__(self)
        self.lock = lock
        self.num = num

    def ThreadTest(self):
        # print(self.name, "-->start")
        sleep(2)
        # print(self.name, "-->finished")

    def run(self):
        with self.num:  # 同时并行指定的线程数量,执行完毕一个则死掉一个线程
            # 以下为需要重复的单次函数操作
            lock.acquire()  # 锁住线程,防止同时输出造成混乱
            print u"现有", threading.enumerate()
            lock.release()
            self.ThreadTest()


if __name__ == "__main__":
    threads=[]
    lock=threading.Lock()
    queue=Queue.Queue()
    num=threading.Semaphore(3)  # 设置同时执行的线程数为3,其他等待执行
    # 启动所有线程
    for i in range(8):  # 总共需要执行的次数
        t=Test(lock,num)
        t.start()
        threads.append(t)

    print '所有执行完毕'

猜你喜欢

转载自www.cnblogs.com/gangdou/p/9144425.html
今日推荐