# coding=utf8
import threading
import time
import random
from threading import Semaphore
threads = []
lock_sm = Semaphore(2)
lock_print = threading.Lock()
class connectdb(threading.Thread):
def run(self):
while True:
lock_sm.acquire()
lock_print.acquire()
print("{}---{} connecting to db... ".format(time.time(),self.name))
print("{}---{} released db...".format(time.time(),self.name))
lock_print.release()
time.sleep(2)
lock_sm.release()
if __name__ == '__main__':
for i in range(5):
threads.append(connectdb())
# 从五个线程取出三个
random_threads = random.sample(threads, 3)
# 阻塞启动线程---------------------------
for t in random_threads:
t.start()
for t in random_threads:
t.join()
Semaphore: 控制已经acquire() 但还未release() 的线程个数